When using the sizeof I always enclose it in parentheses, as it's a bit easier for me to read, even if I can sometimes omit it, in the first case below
sizeof unary-expression
sizeof ( type-name )
My question is how does the parentheses disambiguate things to the compiler? What would be an example where something like:
sizeof char
Would be ambiguous to a compiler?
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.
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.
Accepting a typename after sizeof would not allow all types to be specified in an expression: pointer types (eg: sizeof char * 10) would create an ambiguity complicating the parse, which currently is quite simple.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With