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

前端 未结 4 1553
太阳男子
太阳男子 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:48

    In C the result of the prefix and postfix increment/decrement operators is not an lvalue.

    In C++ the result of the postfix increment/decrement operator is also not an lvalue but the result of the prefix increment/decrement operator is an lvalue.

    Now doing something like (++a)-- in C++ is undefined behavior because you are modifying an object value twice between two sequence points.

    EDIT: following up on @bames53 comment. It is undefined behavior in C++98/C++03 but the changes in C++11 on the idea of sequence points now makes this expression defined.

提交回复
热议问题