Why (and when) do I need to use parentheses after sizeof?

CSizeof

C Problem Overview


The below fails to compile:

typedef int arr[10];
int main(void) {
	return sizeof arr;
}

sizeof.c:3: error: expected expression before ‘arr’

but if I change it to

sizeof(arr);

everything is fine. Why?

C Solutions


Solution 1 - C

According to 6.5.3, there are two forms for sizeof as the following:

sizeof unary-expression
sizeof ( type-name )

Since arr in your code is a type-name, it has to be parenthesized.

Solution 2 - C

That's the way the language is specified, type names must be parenthesized here.

Suppose the grammar looked like this:

sizeof unary-expression sizeof type-name

Now, e.g. the following expression would be ambiguous:

sizeof int * + 0

It could be either sizeof(int *) + 0 or sizeof(int) * +0. This ambiguity doesn't arise for unary expressions, as an asterisk appended to an expression isn't an expression (but for some type names, appending one, is again a type name).

Something had to be specified here and requiring type-names to be parenthesized is a way to solve the ambiguity.

Solution 3 - C

I think it's because you have typedef. If you remove it, it should compile.

Example from wikipedia:

/* the following code fragment illustrates the use of sizeof     
 * with variables and expressions (no parentheses needed),
 * and with type names (parentheses needed)    
 */
char c;
printf("%zu,%zu\n", sizeof c, sizeof (int));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionblueshiftView Question on Stackoverflow
Solution 1 - CIse WisteriaView Answer on Stackoverflow
Solution 2 - CmafsoView Answer on Stackoverflow
Solution 3 - CbazView Answer on Stackoverflow