Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!purdue!mentor.cc.purdue.edu!acu From: acu@mentor.cc.purdue.edu (Floyd McWilliams) Newsgroups: comp.lang.c Subject: Re: The Dangers of sizeof Summary: sizeof is unary op. Keywords: sizeof Message-ID: <2280@mentor.cc.purdue.edu> Date: 10 Apr 89 14:57:52 GMT References: <9969@smoke.BRL.MIL> <3.UUL1.3#5109@pantor.UUCP> <105@servio.UUCP> Reply-To: acu@mentor.cc.purdue.edu (Floyd McWilliams) Organization: PHAP Lines: 51 In article <105@servio.UUCP> penneyj@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 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