cout减去简单打印的输出

Cout subtract the output in simple print

当我使用 cout 打印我的变量值时,如果我在一行或两行中使用两个语句,它不会给我相同的答案。你能帮帮我吗?

int a= 5;
cout << a << endl;
cout << a-- << endl;

cout << a << a-- << endl; 
// it gives me different answer, why?
//they are basically same thing 
cout << a << a-- << endl; 

译为:

cout.operator<<(a).operator<<(a--).operator<<(endl);

在这种情况下,语言不保证首先计算哪个参数。编译器可以自由选择对他们有意义的评估顺序。请注意,函数调用顺序是有保证的,但函数参数的评估顺序是有保证的。

如果您能够使用 ,则 << 运算符的标准已更改。它保证了一个有意义的评估顺序,你会得到预期的结果。

在 C++17 之前 operator << 无法保证求值顺序,但是自从“C++17,从左到右的顺序是 operator <<.[=13= 的保证]

有关详细信息,请参阅 eval_order