【问题标题】:What is the difference in printing a function with a static int with one std::cout and multiple std::cout?打印带有一个 std::cout 和多个 std::cout 的静态 int 函数有什么区别?
【发布时间】:2018-06-27 02:23:40
【问题描述】:

所以当我有这个功能时,我通过多个语句将它打印到控制台,我得到了预期的结果:

0

1

但是当我通过同一行的一个 cout 语句打印出函数时,我得到:

3 2

(这是在之前打印的初始 0 和 1 之后)

为什么会反着打印?

#include "stdafx.h"
#include <iostream>

using namespace std;

int addOne()
{
    static int s_num = -1;
    return ++s_num;
}

int main()
{
    cout << addOne() << "\n";
    cout << addOne() << "\n";
    cout << addOne() << " " << addOne() << "\n";

    return 0;
}

【问题讨论】:

标签: c++ static cout ostream operator-precedence


【解决方案1】:

您实际上是在遇到未指明的行为。在此上下文以及运算符具有相同优先级的任何其他此类上下文中,可以按任何顺序评估函数调用。在这种情况下,编译器选择在第一个函数调用之前评估第二个函数调用,但其他编译器可能会以不同的方式执行。

【讨论】:

  • 这是未指定的行为,而不是未定义的行为。同一内存位置中未排序的修改会导致未定义的行为,但在同一个完整表达式中像 addOne() 这样的函数调用在最坏的情况下是不确定的。
  • 谢谢 - 这是我的意思,但我担心我在这个词上滑倒了。已更正。
  • @aschepler 这未指定的行为,直到 C++17
  • 这里的优先级有什么关系?
猜你喜欢
  • 2015-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-14
  • 1970-01-01
  • 2011-05-19
  • 2013-01-29
相关资源
最近更新 更多