Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!csd4.milw.wisc.edu!lll-winken!uunet!ncrlnk!ncr-sd!hp-sdd!hplabs!hp-ses!hpcuhb!hpcllla!hpclisp!hpclwjm!walter From: walter@hpclwjm.HP.COM (Walter Murray) Newsgroups: comp.lang.c Subject: Re: The Dangers of sizeof Message-ID: <660031@hpclwjm.HP.COM> Date: 13 Apr 89 19:10:23 GMT References: <105@servio.UUCP> Organization: Hewlett-Packard Calif. Language Lab Lines: 35 > 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 -------------