Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disambiguation of sizeof

Tags:

c

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?

like image 960
samuelbrody1249 Avatar asked Feb 10 '21 19:02

samuelbrody1249


Video Answer


2 Answers

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.

like image 98
Eric Postpischil Avatar answered Oct 19 '22 01:10

Eric Postpischil


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.

like image 25
chqrlie Avatar answered Oct 19 '22 02:10

chqrlie