What should "sizeof (expression)" return? Why "8" ??

Wade Guthrie evil at arcturus.UUCP
Fri Dec 9 03:02:07 AEST 1988


Well, I am a relative novice, but how do we learn without trying and
experiencing the flame of disappointment :-)

In article <654 at sbsvax.UUCP>, greim at sbsvax.UUCP (Michael Greim) asks
about the output of the sizeof operator in regards to the following
program:

[abridged for the line counter]
> struct misty {unsigned int a1:1; unsigned int a2:15;}mist;
> int i;
> float r;
> char s [20];
> 
> main ()
> {
> 	printf ("sizeof(mist.a1) [1 bit] = %d\n", sizeof(mist.a1));
> 	printf ("sizeof(c1<c2) = %d\n", sizeof(c1<c2));
> 	printf ("sizeof(i+r) = %d\n", sizeof (i+r));
> 	printf ("sizeof(i+s) = %d\n", sizeof (i+s));
> }

well, each of the sizeofs are in the form of sizeof expression, so
let's dicect each expression to figure out what it should print.  First,

sizeof(mist.a1) -- well, my guess (and this is pretty shakey) is that
mist.a1 is really just a single bit of an unsigned int and not an entity
of itself, so its size is that of an unsigned int, which, on the VAX, is
4 bytes.

sizeof(c1<c2) -- this is an expression, the type of which is independent
of the types of c1 and c2.  A "logical" expression in C is just an integer
expression, and an integer requires 4 bytes on a VAX.

sizeof (i+r) -- well, here we have to look at the promotion rules for 
expressions.  On silly compilers (like that on a VAX running VMS),
all floats get promoted to doubles (rather than having the option of
having them not be promoted to allow single precision math like on SUNs,
but I digress).  So, the float r gets promoted to a double, the other
argument of the binary operator '+' gets promoted to a double, and the
result is a double which, on a VAX, requires 8 bytes (am I doing okay
so far?)

and, lastly, sizeof (i+s) --  s the name of an array of 20 chars.  The
name of an array is a pointer to the zeroth element of that array (pointers
require 4 bytes on a VAX).  Adding an int to a pointer (even in this order)
should provide a pointer -- 4 bytes.

does this help?


Wade Guthrie
Rockwell International
Anaheim, CA

(Rockwell doesn't necessarily believe / stand by what I'm saying; how could
they when *I* don't even know what I'm talking about???)



More information about the Comp.lang.c mailing list