If sizeof
type-name were allowed, then sizeof char * + 3
could be either:
(sizeof (char *)) + 3
, which is the size of a char *
added to 3
or
(sizeof (char)) * (+ 3)
, which is the size of a char
multiplied by + 3
.
Both of those would be valid parsings and fully defined by the standard (aside from the implementation-defined size of the pointer). So accepting sizeof
type-name creates an ambiguity not resolved by the grammar or semantics.
Earlier Example
If sizeof
type-name were allowed, then sizeof char [x]
could be either (sizeof (char)) [x]
(which is a valid expression if x
is a pointer or array; the subscript operator accepts index[array]
) or sizeof (char [x])
(which is a valid expression if x
is an integer; it is the size of an array of x
elements of char
). Further, the grammar would provide no way to distinguish these; both would be valid parsings. Semantic rules could distinguish them based on the type of x
, but then you have to parse before you can evaluate the semantic rules and would need some way for the compiler to undo the parsing.
char
is not a unary expression. [BTW: I allways omit the parentheses if they are not needed, such asstruct stuff *p = malloc(sizeof *p);
] – wildplasser Feb 10 at 19:13sizeof(X)
would invoke the macro rather than the built-in operator. And I can't find my original version of the K&R book, but I seem to recall their examples may have done it that way. – jwdonahue Feb 10 at 19:22