简体   繁体   中英

++ operator on a pointer to struct member

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.

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 .

According to cppreference , the prefix ++ / -- operator has lower precedence thatn the -> operator. The suffix one has the same precedence, but left-to-right associativity.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM