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

Why is the Output of `cout

Linda Hamilton
Release: 2024-12-12 15:10:19
Original
679 people have browsed it

Why is the Output of `cout

Undefined Output of cout << a << a

In the code snippet:

int a = 0;
cout << a++ << a;
Copy after login

it is commonly assumed that the behavior is equivalent to:

cout << (a++) << a;
Copy after login

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);
Copy after login

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
Copy after login

is evaluated as:

std::operator<<<>(std::operator<<<>(E1, E2), E3)
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template