我尝试通过在函数中声明它来打印静态变量的值 5 次,在该函数中每次调用都会增加自身,然后将其添加到全局变量并在 printf 语句中返回其值,但输出与通常的所有静态值不同变量先递增,添加到全局变量后输出顺序相反(所有值都使用单个 printf 语句打印)
#include <stdio.h>
int global_variable = 10;
int fun(){
static int var;
printf("The value of var is %d\n", var);
var++;
return global_variable + var;
}
int main()
{
//This works fine
printf("%d\n", fun());
printf("%d\n", fun());
printf("%d\n", fun());
printf("%d\n", fun());
printf("%d\n", fun());
//This works weird this prints value in reverse order not like the former case
printf("\n%d\n%d\n%d\n%d\n%d\n",fun(), fun(), fun(), fun(), fun());
return 0;
}
Run Code Online (Sandbox Code Playgroud)
第一个输出:
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
Run Code Online (Sandbox Code Playgroud)
第二个输出:
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
Run Code Online (Sandbox Code Playgroud)
在两组代码中,第一个工作正常,但第二个是我不明白的。请解释。