简体   繁体   English

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

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

So when I have this function, and I print it to the console via multiple statements, I get the expected results: 因此,当我具有此功能并通过多条语句将其打印到控制台时,将获得预期的结果:

0

1

But when I print the function out through just one cout statement on the same line, I get: 但是,当我在同一行上仅通过一个cout语句打印出函数时,我得到:

3 2

(This is after the initial 0 and 1 that were previously printed) (这是在先前打印的初始0和1之后)

Why does it print backwards? 为什么会向后打印?

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

You are actually stumbling on unspecified behavior. 您实际上是在绊脚石。 In this context, and any other such context where the operators are of the same precedence, the function calls can be evaluated in any order. 在这种情况下,以及在运算符具有相同优先级的任何其他此类情况下,可以按任何顺序评估函数调用。 In this case, the compiler chose to evaluate the second function call before the first, but other compilers might do it differently. 在这种情况下,编译器选择在第一个函数调用之前评估第二个函数调用,但是其他编译器可能会以不同的方式进行评估。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM