"Joachim Schmitz" <no*********@sc hmitz-digital.dewrite s:
pete wrote:
[...]
>printf's %d being able to display numbers up to 32767,
is irrelevant as to how many padding bytes
(or bytes composed of padding bits),
an object of type unsigned short is allowed to have.
INT_MAX is for int, not short, or unsignd short
(%d prints an int, not an unsigned short)
Right, but we're talking about printing the *size* of an unsigned
short, not its value. The line that led to this long digression was
my own (very slightly sloppy):
printf("Size of s: %d bytes\n", (int)sizeof s);
where s was an object of type unsigned short.
Ah, so you're saying that an int, in addition to it's minimum of 15 value
bits can have as many pading bits (whos's _values_ are unspecified) as it
likes, making the entire sizeof(int) larger than 32727 (as long as it still
fits a size_t)? And not that 'padding _bits_' implies that they are only
allowed to fill up to the next byte size? (the values are explicitly
unspecivied, what about the number?)
The standard says (C99 6.2.6.2p2):
For unsigned integer types other than unsigned char, the bits of
the object representation shall be divided into two groups: value
bits and padding bits (there need not be any of the latter).
For unsigned short, there must be at least 16 value bits (this follows
from the requirement that the range must be at least 0 .. 65535, and
the fact that mathematically you need at least 16 bits to represent
all the values in that range).
The standard places no upper limit on the number of value bits
or on the number of padding bits. sizeof(unsigned short) is
(VB + PB) / CHAR_BIT; VB + PB must be a whole multiple of CHAR_BIT.
This entire discussion is about as close to having no practical
meaning as I can imagine. An implementation that had as many padding
bits for unsigned short as we're talking about, or even as many value
bits, would be beyond exotic; it would be clinically insane.
In practice, I do prefer this:
printf("Size of s: %lu bytes\n", (unsigned long)sizeof s);
to this:
printf("Size of s: %d bytes\n", (int)sizeof s);
but only because it's a good habit, not because I'm the least bit
concerned about the possibility that sizeof s could exceed INT_MAX.
Or the code might be changed so that s is of some larger type (likely
if the code purpose is just to print the sizes of several types).
Note that for ``(int)sizeof(u nsigned short)'' to overflow, almost all
the bits of unsigned short would have to be padding bits. If it had a
huge number N of value bits, then int would have to have at least N-1
value bits (-1 for the sign bit), so it would have more than enough
range to represent the value of sizeof(unsigned short).
--
Keith Thompson (The_Other_Keit h)
ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"