What's the result of += in C and C++?

前端 未结 2 505
长情又很酷
长情又很酷 2020-11-28 09:54

I\'ve got the following code:

#include 
int main(int argc, char **argv) {
    int i = 0;
    (i+=10)+=10;
    printf(\"i = %d\\n\", i);
    re         


        
2条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-28 10:18

    Semantics of the compound assignment operators is different in C and C++:

    C99 standard, 6.5.16, part 3:

    An assignment operator stores a value in the object designated by the left operand. An assignment expression has the value of the left operand after the assignment, but is not an lvalue.

    In C++ 5.17.1:

    The assignment operator (=) and the compound assignment operators all group right-to-left. All require a modifiable lvalue as their left operand and return an lvalue with the type and value of the left operand after the assignment has taken place.

    EDIT : The behavior of (i+=10)+=10 in C++ is undefined in C++98, but well defined in C++11. See this answer to the question by NPE for the relevant portions of the standards.

提交回复
热议问题