What is the correct answer for cout << a++ << a;?

前端 未结 4 468
无人及你
无人及你 2020-11-22 16:12

Recently in an interview there was a following objective type question.

int a = 0;
cout << a++ << a;

Answers:

a. 10

4条回答
  •  长情又很酷
    2020-11-22 17:06

    You can think of:

    cout << a++ << a;
    

    As:

    std::operator<<(std::operator<<(std::cout, a++), a);
    

    C++ guarantees that all side effects of previous evaluations will have been performed at sequence points. There are no sequence points in between function arguments evaluation which means that argument a can be evaluated before argument std::operator<<(std::cout, a++) or after. So the result of the above is undefined.


    C++17 update

    In C++17 the rules have been updated. In particular:

    In a shift operator expression E1< and E1>>E2, every value computation and side-effect of E1 is sequenced before every value computation and side effect of E2.

    Which means that it requires the code to produce result b, which outputs 01.

    See P0145R3 Refining Expression Evaluation Order for Idiomatic C++ for more details.

提交回复
热议问题