Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

sizeof

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?

like image 600
blueshift Avatar asked May 05 '11 08:05

blueshift


People also ask

Is sizeof () a function?

In C language, sizeof( ) is an operator. Though it looks like a function, it is an unary operator.

Why is sizeof called Operator?

Sizeof is a much used operator in the C or C++. It is a compile time unary operator which can be used to compute the size of its operand. The result of sizeof is of unsigned integral type which is usually denoted by size_t.


2 Answers

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.

like image 183
Ise Wisteria Avatar answered Sep 23 '22 11:09

Ise Wisteria


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.

like image 39
mafso Avatar answered Sep 26 '22 11:09

mafso