Reputation: 16946
In the context of C operators precedence. In reality, the following code will be evaluated as follows:
int32_t * result = (int32_t *) addr_base + offset;
|
|
↓
int32_t * result = ((int32_t *) addr_base) + offset;
However, what I see in the table bellow is that cast
and +
should be evaluated from right to left. In other words, in my example +
is right to cast
, so I would expect that the first statement above will be evaluated like this:
int32_t * result = (int32_t *) (addr_base + offset);
As +
is on the right side of cast
(so more priority according to the table).
Why is that actually happening?
Upvotes: 1
Views: 533
Reputation: 48033
Although unary plus has the same precedence as casts, the expression in question involves binary +
, which is two rows lower in the precedence table. So
(int32_t *) addr_base + offset
is unambiguously parsed as
((int32_t *) addr_base) + offset
Upvotes: 1
Reputation: 8614
The +
in row 2 is the unary plus operator. This is similar to the unary negation operator (e.g. x = -y
)
The operator for addition is in row 4 and has a lower precedence than the cast.
In case two operators have the same precedence the order is given by the Associativity (left to right or right to left)
Upvotes: 3
Reputation: 224082
A cast operator has the same precedence as a unary +
operator, but the +
operator in (int32_t) addr_base + offset
is a binary +
operator, which has lower precedence.
A unary operator is one with only one operand. In x = -y;
, the -
is a unary operator. We can also write x = +y;
, where the +
is a unary operator, but this is rarely done since it is largely superfluous.
A binary operator is one with two operands. In x = y + z
, the +
is a binary operator.
Upvotes: 1
Reputation: 1960
The cast operator has higher precedence than addition, so that's why the operand is grouped with the cast operator.
Unary plus has the same precedence as cast. If you were to use those in the same expression, the associativity would go from right to left.
Upvotes: 1