Home >Backend Development >C++ >Why is the Output of `cout

Why is the Output of `cout

Linda Hamilton
Linda HamiltonOriginal
2024-12-12 15:10:19691browse

Why is the Output of `cout

Undefined Output of cout << a << a

In the code snippet:

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

it is commonly assumed that the behavior is equivalent to:

cout << (a++) << a;

However, due to the lack of sequence points between function argument evaluations, the order of execution is not guaranteed. The compiler may evaluate a before or after std::operator<<<>(std::cout, a ).

Therefore, the correct interpretation is:

cout << ((a++) << a);

This means that the result is undefined, as the value of a after the increment is used in the second call to operator<<<>.

C 17 Amendment

In C 17, the rules have been modified such that:

E1 << E2

is evaluated as:

std::operator<<<>(std::operator<<<>(E1, E2), E3)

with all side effects of E1 sequenced before those of E2. This ensures that the code fragment now produces the expected output of "01".

The above is the detailed content of Why is the Output of `cout. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn