Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

++ operator on a pointer to struct member

Tags:

c

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.

like image 480
zacharoni16 Avatar asked Dec 20 '22 00:12

zacharoni16


2 Answers

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.

like image 162
John Bode Avatar answered Jan 06 '23 06:01

John Bode


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.

like image 32
Sami Kuhmonen Avatar answered Jan 06 '23 05:01

Sami Kuhmonen