sizeof() and parenthesis in C

Tags: / c /

About the two kinds of usages of the sizeof operator in C. One with parenthesis, and the one without..

From my old blog.


The sizeof operator in C will sometimes work without parenthesis but sometimes won't.

#include<stdio.h>
int main()
{
    int a;
    printf("\n%d", sizeof a);
    printf("\n%d", sizeof(a));
    return 0;
}

In this case, sizeof will work regardless of the use of parenthesis.

Consider another example:

#include<stdio.h>
int main()
{
    printf("\n%d", sizeof int);
    return 0;
}

Here, in

printf("\n%d", sizeof int);

we are trying to print the size (in bytes) of the int data-type.

This will give an error:

main.c: In function ‘main':
main.c:4:27: error: expected expression before ‘int'
    printf("\n%d", sizeof int);
                ^~~

But add parenthesis to the sizeof operator use,

printf("\n%d", sizof(int));

and the program will work.

Strange isn't it?

But it turns out that this is because of the way things are specified in the standard.

As per the standard (under section 6.5.3 in this draft of C99), sizeof has two forms:

sizeof int didn't work because int is a data-type and hence the second form of sizeof must be used. This case is applicable to typedef-ed names as well.

I found a nice example for the need of parenthesis in the second version in this post.

Consider the expression

sizeof int * + 0

There are no parenthesis. So it could be

sizeof(int) * (+0) 

or

sizeof(int *) + 0

Use of parenthesis helps avoid this ambiguity.

References