Reputation: 610
In "C++ primer 5th edition" on page 228
The table Table 4.4. Operator Precedence
shows operators and associativitiy of operands.
What I am confused about is in this table says that Prefix increment/decrement is Right-To-Left associative and also Postfix increment/decrement also Right-To-Left So there's the letter "R" that means right to left. But in www.cppreference.com
I see that postfix increment/decrement are Left-To-Right associative.
If someone makes things clear up through giving an example containing Compound expression, then is really appreciated.
Upvotes: 0
Views: 935
Reputation: 7257
Prefix operators are Right to Left associative:
https://en.cppreference.com/w/cpp/language/operator_precedence
Neither C++ Primer 5th edition from Prata nor from Lippman have any operator priority table on page 228.
Upvotes: -1
Reputation: 2552
There's no book safe from Errata. Each version of a book adds some enhancements and corrects some mistakes. The author is always appreciating Errata reporting. Anyway: The post-fix increment and -decrement are Left-To-Right associative.
int x = 5;
x++;
As you can see from the expression above: the operand x
is at the lhs
of the operator ++
thus you easily can understand it.
++x;
Now the operand x
is on the right thus Pre-increment/decrement is Right-To-Left.
Upvotes: 0
Reputation: 76305
The C++ grammar defines a postfix expression like this:
postfix-expression:
primary-expression
...
postfix-expression ++
....
In parsing a ++ ++
, a
is a primary-expression, so a ++
is a postfix-expression. The final ++
applies to the result of that postfix-expression.
In short, ++
groups left to right.
The same thing applies to all of what we usually think of as postfix operators: they apply to a postfix-expression, so they group left to right.
As mentioned in a comment, going the other way would make ptr[i]++
rather funky.
Looking at a (probably illegal) PDF version of that book that I found online, I suspect the the entries for postfix++ and postfix-- are cut-and-paste typos. Both of those operators are supposedly described on page 147, as are prefix++ and prefix--, but the only discussion there is about prefix++ and prefix--.
Upvotes: 5