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

前端 未结 3 1858
感动是毒
感动是毒 2021-01-04 09:42

Defined this way, we can do neither ++x++ nor ++x--. But on the other hand, both (++x)++ and (++x)-- are useful expressio

相关标签:
3条回答
  • 2021-01-04 10:01

    (++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.

    0 讨论(0)
  • 2021-01-04 10:07

    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.

    0 讨论(0)
  • 2021-01-04 10:08

    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.

    0 讨论(0)
提交回复
热议问题