繁体   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?

因此,当我具有此功能并通过多条语句将其打印到控制台时,将获得预期的结果:

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

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

暂无
暂无

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

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