尝试从printf语句中的函数打印静态变量时出现奇怪的输出
我尝试通过在函数中声明它来打印静态变量的值 5 次,在该函数中每次调用都会增加自身,然后将其添加到全局变量并在 printf 语句中返回其值,但输出与通常的所有静态值不同变量先递增,添加到全局变量后输出顺序相反(所有值都使用单个 printf 语句打印)
#include <stdio.h>
int global_variable = 10;
int fun(){
static int var;
printf("The value of var is %dn", var);
var++;
return global_variable + var;
}
int main()
{
//This works fine
printf("%dn", fun());
printf("%dn", fun());
printf("%dn", fun());
printf("%dn", fun());
printf("%dn", fun());
//This works weird this prints value in reverse order not like the former case
printf("n%dn%dn%dn%dn%dn",fun(), fun(), fun(), fun(), fun());
return 0;
}
第一个输出:
The value of var is 0
11
The value of var is 1
12
The value of var is 2
13
The value of var is 3
14
The value of var is 4
15
第二个输出:
The value of var is 5
The value of var is 6
The value of var is 7
The value of var is 8
The value of var is 9
20
19
18
17
16
在两组代码中,第一个工作正常,但第二个是我不明白的。请解释。
回答
函数参数的计算顺序未指定。这意味着它们可以按任何顺序进行评估。
关于函数调用的C 标准第 6.5.2.2p10 节指出:
在函数指示符和实际参数的计算之后但在实际调用之前有一个序列点。调用函数(包括其他函数调用)中的每个在被调用函数体执行之前或之后没有特别排序的评估都相对于被调用函数的执行而言是不确定的。
在这种情况下,func在给定的表达式中不要多次调用是合适的,或者更准确地说,在没有中间序列点的情况下不要多次调用。