The Dangers of sizeof
Floyd McWilliams
acu at mentor.cc.purdue.edu
Tue Apr 11 00:57:52 AEST 1989
In article <105 at servio.UUCP> penneyj at servio.UUCP (D. Jason Penney) writes:
>sizeof (aType) is actually the same as
>sizeof (aType)(1)
>(i.e, casting the empty expression). People who uniformly treat sizeof
>as if it were a function run a grave risk. 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))
Oh really? Then take a look at this:
--
Script started on Sun Apr 9 13:41:38 1989
tcsh% more foo.c
#include <stdio.h>
main()
{
printf("sizeof(char) - 1 == %d.\n",sizeof(char) - 1);
}
tcsh% cc foo.c
tcsh% a.out
sizeof(char) - 1 == 0.
tcsh%
script done on Sun Apr 9 13:42:09 1989
--
>I recommend ALWAYS using the operator form of sizeof and parenthesizing
>the entire sizeof expression for safety. Note: you MUST parenthesize
>the operand of sizeof if it is a type:
>(sizeof (char)) - 1
"sizeof" may not be a function, but it does have a high precedence
(it's a unary operator). If what you posted were true, then everyone who
tried a "sizeof(foo) + CONST" under pre-ANSI standard C would have been
screwed; C didn't have a unary plus.
--
"Life's for my own, to live my own way."
Floyd McWilliams mentor.cc.purdue.edu!acu
More information about the Comp.lang.c
mailing list