简体   繁体   English

使用本地静态变量调用函数

[英]Call function with local static variable

Assume that we have simplest function with local static variable: 假设我们使用本地静态变量具有最简单的函数:

int f()
{
    static int a = 0;
    return ++a;
}

Let's call this function multiple times and print result: 让我们多次调用此函数并打印结果:

int main()
{
    int a  = f();
    int b  = f();
    std::cout<<a<<b;
}

Output is "12" - ok, as expected. 输出为“12” - 正如预期的那样。 But this call 但是这个电话

int main()
{
   std::cout<<f()<<f();
}

produces reverse order - "21" . 产生相反的顺序 - “21” Why? 为什么?

Because the order in which functions are executed in a compound statement is undefined. 因为在复合语句中执行函数的顺序是未定义的。 This means that by the end of the std::cout<<f()<<f() line, you are guaranteed to have called f() twice, and you are guaranteed to have printed the two results, but which result is first is not defined and can vary across compilers. 这意味着在std::cout<<f()<<f()行结束时,保证两次调用f() ,并保证打印出两个结果,但结果是第一个没有定义,可以在编译器之间变化。

There is a difference because f() has side effects. 有区别因为f()有副作用。 Side effects are results of the function that can't be measured by its return value. 副作用是无法通过其返回值测量的函数的结果。 In this case, the side effect is that the static variable is modified. 在这种情况下,副作用是修改静态变量。 If the function had no side effect (or if you were calling multiple functions with no overlapping side effects), which function is called first wouldn't change anything. 如果函数没有副作用(或者如果你调用多个函数没有重叠的副作用),那么首先调用哪个函数不会改变任何东西。

This has been asked/answered before: what is wrong here? 之前有人问过/回答: 这里有什么问题? associativity? 关联? evaluation order? 评估顺序? how to change order? 如何改变秩序?

Not all operators are ordered in C++. 并非所有运算符都是用C ++命令的。 The link has a good explanation. 该链接有一个很好的解释。

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

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