Why does postfix operator++ have higher precedence than prefix operator++?

荒凉一梦 提交于 2019-12-01 03:32:52

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.

(++x)++ increments x 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 to x+1 but completely avoids having to call operator+, 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 call operator++ and operator-- 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.

Prasoon Saurav

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!