Topic: sizeof(type-id) concatenations


Author: "Larry Brasfield" <larrybr@seanet.com>
Date: 1999/07/27
Raw View
I recently encountered a magazine article (#)
where a complaint was aired because a C/C++
compiler accepts the following expression:
    sizeof(int) sizeof(char) sizeof(short)
With minimal effort, that can be parsed thusly:
    sizeof ( (int) (sizeof ((char) sizeof(short))) )

(# Ron Burk's "Bug++ of the Month" in the August
1999 issue of "Windows Developer's Journal")

This situation raises a couple questions with me.

1. Is there any reason not to simply apply the
 right-associativity and equal precedence of
 the cast and sizeof operators to derive the
 parse forced above with extra parenthesis?
 (Alternatively, is the first expression invalid?)

2. If no to question 1, is this not so obvious
 that a respectable programmer's magazine
 (editor) should experience at least some
 embarassment over diagnosing a compiler's
 acceptance of the first expression as a bug?


--
Larry Brasfield
Above opinions may be mine alone.
X-Replace-Address
(Humans may reply at unundered larry_br@sea_net.com )



[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]






Author: "Darin Adler" <darin@bentspoon.com>
Date: 1999/07/28
Raw View
Larry Brasfield <larrybr@seanet.com> wrote:

> I recently encountered a magazine article (#)
> where a complaint was aired because a C/C++
> compiler accepts the following expression:
>     sizeof(int) sizeof(char) sizeof(short)
> With minimal effort, that can be parsed thusly:
>     sizeof ( (int) (sizeof ((char) sizeof(short))) )

The first expression is invalid.

It's true that cast and sizeof have equal precedence and that unary
operators are right-associative.

However, sizeof must be followed by a unary-expression, or a parenthesized
type-id. A cast-expression with a cast in it, like "(char) sizeof(short)",
is not a unary-expression. See section 5.3 of the C++ standard for the
production that defines unary-expression.

Adding parentheses turns the cast-expression into a primary-expression, and
every primary-expression is a unary-expression. Thus, "((char)
sizeof(short))" is a unary-expression. See section 5.1 for the production
that defines primary-expression.

    -- Darin
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]