Reputation: 307
I came across a piece of code that reads:
++myStruct->counter
I'm confused on how the ++ operator and -> operator are evaluated here. The ++ has precedence over the -> operator and left to right evaluation. It appears the ++ operator would actually perform pointer arithmetic on 'myStruct', not increment the counter member.
Upvotes: 4
Views: 487
Reputation: 123448
The ++ has precedence over the -> operator and left to right evaluation.
This is not correct - postfix operators like ->
have higher precedence than unary (prefix) operators ++
and --
. The expression is parsed as
++(myStruct->counter)
so the counter
member of myStruct
is being incremented.
Upvotes: 5
Reputation: 63124
According to cppreference, the prefix ++
/--
operator has lower precedence thatn the ->
operator. The suffix one has the same precedence, but left-to-right associativity.
Upvotes: 3
Reputation: 31143
The postfix increment and decrement have the same precedence as the ->
operator and left-to-right associativity, but the prefix increment and decrement are after. So the code does increment the variable counter
and not the myStruct
.
Upvotes: 3