Search code examples
c++prefixpostfix-operator

Prefix increment operator error C++


I'm guessing it's to do with precedence but why is this legal

vector<string>::iterator iter = vec.begin();
iter++->empty();

But this is not.

vector<string>::iterator iter = vec.begin();
++iter->empty();

Can someone try to explain the chain of event that happen here.


Solution

  • The arrow operator has higher precedence than increment, so ++iter->empty() is parsed as ++(iter->empty()), not (++iter)->empty(). The post-increment version works because there's only one way to parse iter++->empty().