C++库特脸红的奇怪行为。

C++ strange behaviour of cout's flush.

本文关键字:C++      更新时间:2023-10-16

请考虑以下代码。 预期输出应为
0 1
1 2
2 3
等等。

#include<iostream>
using namespace std;
int f=0;
int B()
{
  return f; 
}
int A()
{
  return f++;
}
int main()
{
  cout<<A()<<" "<<B()<<endl;
  cout<<A()<<" "<<B()<<endl;
  cout<<A()<<" "<<B()<<endl;
  cout<<A()<<" "<<B()<<endl;
  return 0;
}

但实际输出是
0 0
1 1
2 2
等等..为什么?

如果我像这样更改代码-

int main()
{
  int f=0;
  cout<<f++<<" "<<f<<endl;
  cout<<f++<<" "<<f<<endl;
  cout<<f++<<" "<<f<<endl;
  cout<<f++<<" "<<f<<endl;
  return 0;
}

然后我得到正确的预期输出
为什么?

未指定<<操作数的计算顺序。所以

cout << A() << " " << B() << endl;

可以被视为:

temp1 = A();
temp2 = B();
cout << temp1 << " " << temp2 << endl;

或作为:

temp2 = B();
temp1 = A();
cout << temp1 << " " << temp2 << endl;

对变量执行副作用并在没有定义排序的情况下访问它会导致未定义的行为。

相关文章:
  • 没有找到相关文章