打印一个带有静态 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?
所以当我有这个函数,并通过多个语句将其打印到控制台时,我得到了预期的结果:
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;
}
您实际上偶然发现了未指定的行为。在此上下文以及运算符具有相同优先级的任何其他此类上下文中,可以按任何顺序计算函数调用。在这种情况下,编译器选择在第一次函数调用之前计算第二个函数调用,但其他编译器可能会以不同的方式执行。
相关文章:
- std::cout.imbue()多重调用
- 如何在C++中用std::cout正确显示带十六进制的字符串文本
- 为什么在C的循环中使用printf的Rust代码不显示输出,而在C++的循环中显示std::cout
- 为什么我应该在异常处理中使用std::cerr而不是std::cout
- std::cout输出int时出现编译错误
- 在这种情况下显式调用时,std::cout 如何更改析构函数的行为?
- 为什么 std::cout 打印浮点数、双精度和长双精度到相同的小数精度?
- 为什么我需要做'using namespace std'而不是"使用 std::cout"?
- main() 中的 std::cout 在调试期间不会在调试控制台中打印任何内容
- 错误:在尝试检测 std::cout 是否<< t 时,功能强制转换为数组类型;有效
- std::cout 来自多个线程
- 在 c++ 中以十六进制格式打印无符号字符(BYTE).使用 std::cout
- Cuda 基本程序 (将值写入矩阵和 std:cout 不起作用) ;主功能不启动
- 使用 std::addressof(std::cout) 而不是 &std::cout 是否有任何风险?
- 是否可以为 std::cout 创建别名?
- std::cout 在打印变量与函数表达式时的行为不同
- 带有 std::cout 的多线程控制台文本动画
- 为什么在语句"std::cout << std::endl;"中使用时需要命名空间限定,给定依赖于参数的查找?
- "std::cout << std::endl;"如何编译?
- std::cout/std::cerr seg faults