The Dangers of sizeof

D. Jason Penney penneyj at servio.UUCP
Sat Apr 8 04:33:50 AEST 1989


In article <510 at lakesys.UUCP> chard at lakesys.UUCP (Chad Gibbons) writes:
> sizeof comes in two flavors, sizeof(type) and sizeof object.  In the
> latter case the object-expression is not evaluated, only its type is
> used.  Therefore the above usage is perfectly legitimate.  As to
> whether it is better or worse than the alternative style, there
> don't seem to be really strong arguments on either side.  I personally
> prefer sizeof(type) since to me the other form is just a corruption of
> this fundamental definition, but I'm sure other programmers disagree.
> It doesn't seem to be worth arguing about..


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

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))

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

-- 
D. Jason Penney                  Ph: (503) 629-8383
Servio Logic Corporation       uucp: ...ogccse!servio!penneyj
15220 NW Greenbrier Parkway #100
Beaverton, OR 97006



More information about the Comp.lang.c mailing list