The Dangers of sizeof
Walter Murray
walter at hpclwjm.HP.COM
Fri Apr 14 05:10:23 AEST 1989
> Trick question: what is the value of:
>
> sizeof (char) - 1
>
> Answer: 1
I know that many others will point out that this is wrong. But wait:
there *IS* reason for confusion.
If you just look at page 49 of K&R (page 53 in the 2nd edition),
you will think that sizeof, (type), and unary - are operators with
the same precedence, and that they associate right-to-left. By that,
the answer *SHOULD* be 1, shouldn't it?
On page 188 (first edition) you find "the rest of the story": They tell
you that sizeof(type) "is to be taken as a unit". In other words,
the sizeof operator actually has higher precedence than a cast. In the
second edition, I can't find any place where that is spelled out in so
many words, though it does follow from the syntax rules that are given.
(A "cast-expression" is now distinct from a "unary-expression".)
I hope the precedence table gets updated in some future edition. Another
problem in the table (troublesome only for novices) is that operators
like "-" appear twice, once as unary and once as binary. But now I'm
drifting.
Back to the original problem, Harbison & Steele also comment on it
(2nd edition, page 156). They see it as a syntactic ambiguity which
is resolved arbitrarily.
The pANS resolves it, of course, by having unary operators (like
sizeof) at a higher precedence than cast operators.
Walter Murray
-------------
More information about the Comp.lang.c
mailing list