sizeof()
and parenthesis in CThe sizeof
operator in C will sometimes work without
parenthesis but sometimes won't.
#include<stdio.h>
int main()
{
int a;
("\n%d", sizeof a);
printf("\n%d", sizeof(a));
printfreturn 0;
}
In this case, sizeof
will work regardless of the use of
parenthesis.
Consider another example:
#include<stdio.h>
int main()
{
("\n%d", sizeof int);
printfreturn 0;
}
Here, in
("\n%d", sizeof int); printf
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,
("\n%d", sizof(int)); printf
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 unary-expression
sizeof(type-name)
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.