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

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

    For anybody who might want the precise details of the differences as they're stated in the standards, C99, §6.5.3/2 says:

    The value of the operand of the prefix ++ operator is incremented. The result is the new value of the operand after incrementation.

    By contrast, C++11, §5.3.2/1 says:

    The result is the updated operand; it is an lvalue, and it is a bit-field if the operand is a bit-field.

    [emphasis added, in both cases]

    Also note that although (++a)-- gives undefined behavior (at least in C++03) when a is an int, if a is some user-defined type, so you're using your own overloads of ++ and --, the behavior will be defined -- in such a case, you're getting the equivalent of:

    a.operator++().operator--(0);
    

    Since each operator results in a function call (which can't overlap) you actually do have sequence points to force defined behavior (note that I'm not recommending its use, only noting that the behavior is actually defined in this case).

提交回复
热议问题