打印一个带有静态 int 的函数,有一个 std::cout 和多个 std::cout 有什么区别?

What is the difference in printing a function with a static int with one std::cout and multiple std::cout?

本文关键字:cout std 有一个 区别 什么 一个 打印 int 静态 函数      更新时间:2023-10-16

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

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;
}

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