Defined this way, we can do neither ++x++
nor ++x--
. But on the other hand, both (++x)++
and (++x)--
are useful expressio
(++x)++
incrementsx
by two and returns the value "in the middle"
Why not (x += 2) - 1
or (++x, x++)
? Both seem to be clearer. For scalars, both are well-defined also in C++03, as opposed to your proposed expression.
(++x)--
is essentially equivalent tox+1
but completely avoids having to calloperator+
, which can be quite useful sometimes.
That's an arbitrary statement without any explanation. So I'm going to throw into the pool:
x+1
is essentially equivalent to(++x)--
but completely avoids having to calloperator++
andoperator--
which can be useful sometimes.
So why is the precedence not defined to have ++x++ automatically expand to (++x)++ rather than ++(x++)
Just to make such arcane corner cases not error out? No way. Can you please recite man operator
for me? If you cannot do that, better not try and write ++x++
in your code.
C++ standard just kept the C rules and obviously those weren't fixed considering operator overloading and idioms yet be invented in a yet to be invented language.
Looking at what is available in D.M. Ritchie Home Page, on see that this precedence is already present in B (Unary operators are bound right to left. Thus -!x++
is bound -(!(x++))
in Users' Reference to B) and I didn't see increment operators in BCPL.
Both (++x)++
and (++x)--
invoke undefined behaviour [assuming x to be a primitive type]. For user defined type the scenario would be different. However it is not generally recommended to use such confusing expressions in your code.
As far as the precendence is concerned this answer explains why post increment has higher precedence than pre increment.