The result of int c=0; cout<<c++<<c;

后端 未结 5 1897
无人及你
无人及你 2020-12-06 19:29

I think it should be 01 but someone says its \"undefined\", any reason for that?

5条回答
  •  失恋的感觉
    2020-12-06 20:03

    c++ is both an increment and an assignment. When the assignment occurs (before or after other code on that line) is left up to the discretion of the compiler. It can occur after the cout << or before.

    This can be found in the C99 standard http://www.open-std.org/JTC1/SC22/wg14/www/docs/n1124.pdf

    You can find it on page 28 in the pdf or section 5.1.2.3

    the actual increment of p can occur at any time between the previous sequence point and the next sequence point

    Since someone asked for the C++ standard (as this is a C++ question) it can be found in section 1.9.15 page 10 (or 24 in pdf format)

    evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced

    It also includes the following code block:

    i = v[i++]; // the behavior is undefined
    i = 7, i++, i++; // i becomes 9
    i = i++ + 1; // the behavior is undefined
    

    I feel that the C99 standard's explanation is clearer, but it is true in both languages.

提交回复
热议问题