Exercise 4.20 of C++ Primer, 5e asks whether the expression iter++->empty();
is legal. Assume that iter
is a vector<string>::iterator
.
This expression is legal. I compiled it with gcc, and the answers to another question on Stack Overflow have addressed this much. However, I'm confused as to why it is legal.
This answer to a similar question gives the following as an equivalent pair of expressions:
iter->empty();
iter++;
The operator precedence table in my book lists ->
as having higher precedence than the postfix ++
operator. This matches the explicit order of operations in the equivalent code above. However, I am used to seeing operators apply to whatever is right next to them. In the case of ->
, I expected the compiler would to apply it to ++
(by itself, without iter
) and throw an error. In other words, I tried to parenthesize the original expression as iter(++->empty());
, which is obviously illegal.
So, it seems like c++ requires compilers to parse expressions in a more complex way than just parenthesizing based on precedence and associativity. Is that right? If there is an easy way to explain how this actually happens, I would like to know about it.
iter
from?iter++
has to bind first. Also, your book is wrong, or you're misreading it; postfix++
has the same precedence as->
(prefix++
has lower precedence than either, but it's not involved here).