The Dangers of sizeof

Guy Harris guy at auspex.auspex.com
Tue Apr 11 05:20:40 AEST 1989


 >I must disagree!

So must I, but that's because I know for a fact that you're wrong.

 >There is only ONE form of sizeof -- the operator form,
 >which takes an arbitrary (unevaluated) expression as its argument.

Wrong.  "sizeof" is, indeed, an operator in both forms; however, the
notion that

 >sizeof (aType) is actually the same as
 >
 >sizeof (aType)(1)
 >
 >(i.e, casting the empty expression).

is not backed up by any language specification I've seen.  K&R I has two
separate grammar rules for the two forms; the December 7, 1988 (d)pANS
says that

	...The 'sizeof' operator yields the size (n bytes) of its
	operand, which may be an expression or the parenthesized name of
	a type.

 >Trick question:  what is the value of:
 >
 >sizeof (char) - 1
 >
 >Answer:  1 -- the (char) is a cast, which is of higher precedence than
 >sizeof, hence it parses as,
 >
 >sizeof ((char)(- 1))

Yeah, that must *be* a trick question, considering you got it wrong. 
The answer is 0, not 1; the "(char)" is *NOT* a cast, it's part of the
"sizeof" expression, so it parses as

	(sizeof (char)) - 1

Are you sure you didn't mean to post this on April 1?



More information about the Comp.lang.c mailing list