What does sizeof without () do? [duplicate]
So if we look at the grammar for sizeof
in the C99 draft standard section 6.5.3
Unary operators paragraph 1 it is as follows:
sizeof unary-expression
sizeof ( type-name )
There is a difference you can not use a type-name without parenthesizes and section 6.5.3.4
The sizeof operator paragraph 2 says(emphasis mine):
The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type.[...]
For completeness sake you may wonder if we can use sizeof
with an expression if we have parenthesizes and the answer is yes since a unary-expression can itself contain parenthesizes. The easiest way to see this would be to look section A.2.1
Expressions from the draft standard and work through the grammar like so:
unary-expression -> postfix-expression -> primary-expression -> ( expression )
sizeof
is an operator, not a function, so you don't need the ()
if the operand is an expression (but you normally use them). sizeof * q == sizeof(*q)
. Note that if the operand is a type, you need to use the ()
, so sizeof(int)
(see for example http://en.wikibooks.org/wiki/C_Programming/Reference_Tables)
sizeof sizeof operator for expressions sizeof 123
sizeof() sizeof operator for types sizeof (int)
Now even the wiki is full of informations about C... The world is changing fast :-)
The sizeof operator is used to determine the amount of space a designated datatype would occupy in memory. To use sizeof, the keyword "sizeof" is followed by a type name or an expression (which may be merely a variable name). If a type name is used, it must always be enclosed in parentheses, whereas expressions can be specified with or without parentheses.
sizeof
is an operator, specifically a unary operator like unary &
or ++
. It takes either a unary expression or a type name surrounded by parens as its operand.
The syntax is
sizeof unary-expression sizeof ( type-name )
So, given a declaration like
int *q;
the expressions sizeof *q
and sizeof (int)
are equivalent, as are sizeof q
and sizeof (int *)
.
The same thing it does with parens - it returns the size of whatever you pass it, in this case the size of whatever is pointed to by q
.
It's somewhat less clear, though, especially when we get involved with complex calls to malloc
and sizeof
, so I consider it to be best practice to always use the parens.
The same thing as sizeof with parantheses. It'a a right side unary operator, so it treats its right size as operand.
As far as I know paranthesis are obligatory when using sizeof with basic data types.
When you have a variable int a
you can check its size both ways, parantheses are not mandatory: sizeof a
, sizeof (a)
will work the same.
But when checking size of int itself only sizeof (int)
will work.