gpt4 book ai didi

c - 尝试从 printf 语句中的函数打印静态变量时出现奇怪的输出

转载 作者:行者123 更新时间:2023-12-02 02:18:40 25 4
gpt4 key购买 nike

我尝试打印静态变量的值 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;
}

第一个输出:

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 standard 第 6.5.2.2p10 节关于函数调用状态:

There is a sequence point after the evaluations of the function designator and the actual arguments but before the actual call. Every evaluation in the calling function (including other function calls) that is not otherwise specifically sequenced before or after the execution of the body of the called function is indeterminately sequenced with respect to the execution of the called function.

在这种情况下,在给定表达式中不要多次调用 func 是正确的,或者更准确地说,在没有中间序列点的情况下不要多次调用。

关于c - 尝试从 printf 语句中的函数打印静态变量时出现奇怪的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66782538/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com