【问题标题】:C++ strange behaviour of cout's flush. [duplicate]cout 刷新的 C++ 奇怪行为。 [复制]
【发布时间】:2017-02-04 09:31:15
【问题描述】:

考虑以下代码。预期输出应该是
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;
}

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

【问题讨论】:

  • 所有那些&lt;&lt; 只是隐藏了一堆正常的函数调用。评估函数调用的参数的顺序是未定义的。因此,标准没有定义调用A()B() 的顺序。 (f++f 也是如此,只是结果不同)。

标签: c++ cout flush


【解决方案1】:

&lt;&lt; 的操作数的计算顺序未指定。所以

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

可以被视为:

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

或作为:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-21
    • 1970-01-01
    • 2011-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多