Why are multiple increments/decrements valid in C++ but not in C?

前端 未结 4 1520
太阳男子
太阳男子 2021-01-18 05:09

test.(c/cpp)

#include 

int main(int argc, char** argv)
{
  int a = 0, b = 0;
  printf(\"a = %d, b = %d\\n\", a, b);
  b = (+         


        
4条回答
  •  无人共我
    2021-01-18 05:38

    In C and C++, there are lvalue expressions which may be used on the left-hand side of the = operator and rvalue expressions which may not. C++ allows more things to be lvalues because it supports reference semantics.

    ++ a = 3; /* makes sense in C++ but not in C. */
    

    The increment and decrement operators are similar to assignment, since they modify their argument.

    In C++03, (++a)-- would cause undefined behavior because two operations which are not sequenced with respect to each other are modifying the same variable. (Even though one is "pre" and one is "post", they are unsequenced because there is no ,, &&, ?, or such.)

    In C++11, the expression now does what you would expect. But C11 does not change any such rules, it's a syntax error.

提交回复
热议问题