Reputation: 23
What does sizeof (int) * p
semantically mean? Is it:
1. sizeof( (int) *p )
or
2. ( sizeof(int) ) * p
and what rule makes the expression to be evaluated this way?
Upvotes: 2
Views: 1619
Reputation: 123458
sizeof
is a unary operator, which has a higher precedence than binary *
, so the expression sizeof (int) * p
is parsed as (sizeof (int)) * p
. Here's the parse tree:
*
/ \
sizeof p
|
(int)
Edit
From onezero's comment:
but can't the expression be evaluated like sizeof( (int) *p ) ,as sizeof operator, type-cast operator and *(dereference) operator have same precedence and associates from right to left?
Here's the relevant syntax (from the ballot draft of the C2011 standard):
(6.5.3) unary-expression: postfix-expression ++ unary-expression -- unary-expression unary-operator cast-expression sizeof unary-expression sizeof ( type-name ) alignof ( type-name )
As you can see, the (int)
is interpreted as part of the sizeof
expression, full stop. It is not interpreted as part of a cast-expression. The syntax doesn't allow sizeof
to be followed directly by a cast-expression; there must be a unary-operator (one of &
, *
, +
, -
, ~
, !
) between them.
Upvotes: 4
Reputation: 2773
Doesn't it depend what p is?
void main() { int p = 3; printf("%d", sizeof(int) *p); }
Will output 12.
void main() { char *p = "a"; printf("%d", sizeof((int) *p)); }
Will output 4.
Upvotes: -1