Re: Plauger, size_t and ptrdiff_t
- From: "P.J. Plauger" <pjp@xxxxxxxxxxxxxx>
- Date: Fri, 17 Feb 2006 05:43:46 -0500
"Keith Thompson" <kst-u@xxxxxxx> wrote in message
news:ln1wy2e71y.fsf@xxxxxxxxxxxxxxxxxx
"robertwessel2@xxxxxxxxx" <robertwessel2@xxxxxxxxx> writes:
In another thread, a poster mentioned the Posix ssize_t definition
(signed version of size_t). My initial reaction was to wonder what the
point of the Posix definition was when ptrdiff_t was already defined as
such.
I got the idea that ptrdiff_t had to be the same size as size_t from
Plauger's "The Standard C Library," where he states "... It is always
the signed type that has the same number of bits as the4 unsigned type
chosen for size_t..." This language would not rule out one being int
and the other long so long as sizeof(int)==sizeof(long) for the
implementation.
Now I can't see anywhere in the standard that would require that, at
least not directly, and it seems that a size_t of unsigned int and a
prtdiff_t of long (where int and long are different sizes) would be
possible. C99 defines SIZE_MAX as being at least 65535, and
PTRDIFF_MIN/MAX as being at least -/+65535.
So do size_t and ptrdiff_t have to be the same size (or base type) or
not?
There's no requirement in the standard for size_t and ptrdiff_t to be
the same size, but I don't know of any implementation where they
differ.
ptrdiff_t is "the signed integer type of the result of subtracting two
pointers"; size_t is "the unsigned integer type of the result of the
sizeof operator".
Suppose a system only supports objects up to 65535 bytes. The sizeof
operator can only yield values from 0 to 65535, so 16 bits are
sufficient, but pointer subtraction for pointers to elements of an
array of 65535 bytes could yield values from -65535 to +65535, so
ptrdiff_t would have to be at least 17 bits.
Yes, but. X3J11 was painfully aware of this problem, which is why
we explicitly decided to allow some pointer differences to be
unrepresentable as a ptrdiff_t. I said what I said because that
was the reality at the time and it was certainly the intent of the
committee. Whether it got captured well in words...
BTW, even when you do get a ptrdiff_t overflow, on a (very common)
twos-complement machine with quiet wraparound on overflow there are
remarkably few cases where it matters.
P.J. Plauger
Dinkumware, Ltd.
http://www.dinkumware.com
.
- Follow-Ups:
- Re: Plauger, size_t and ptrdiff_t
- From: Malcolm
- Re: Plauger, size_t and ptrdiff_t
- From: Keith Thompson
- Re: Plauger, size_t and ptrdiff_t
- References:
- Plauger, size_t and ptrdiff_t
- From: robertwessel2@xxxxxxxxx
- Re: Plauger, size_t and ptrdiff_t
- From: Keith Thompson
- Plauger, size_t and ptrdiff_t
- Prev by Date: Re: file into dynamic arrays
- Next by Date: Re: a simple problem about printf("%10.5f",f)
- Previous by thread: Re: Plauger, size_t and ptrdiff_t
- Next by thread: Re: Plauger, size_t and ptrdiff_t
- Index(es):
Relevant Pages
|