gpt4 book ai didi

无法理解静态变量的行为

转载 作者:行者123 更新时间:2023-11-30 15:55:29 24 4
gpt4 key购买 nike

#include <stdio.h>

main()
{

int i = 10;
static int a = i;
if(a==10)
printf("yes 1st comparision is equal\n");
else
printf("no 1st comparision is not equal\n");
if(i==10)
printf("yes 2nd comparision is equal\n");
else
printf("no 2nd comparision is not equal\n");

a=15;
if(a==i)
printf("yes 3rd comparision is equal\n");
else
printf("no 3rd comparision is not equal\n");

}

为什么a重新初始化为15,输出是no 3rd comparision is not equal而输出应该是 yes 3rd comparision is equal?

最佳答案

您正在比较的是两个单独的值。

从您的问题来看,您似乎期望的是引用(通常使用指针来实现)。

这个例子与静态无关,因为函数main只输入一次。

如果您想要引用,这是一个非常简化的用法:

#include <stdio.h>

int main() {
int i = 10;
int* const a = &i;
if (*a == 10)
printf("yes 1st comparision is equal\n");
else
printf("no 1st comparision is not equal\n");
if (i == 10)
printf("yes 2nd comparision is equal\n");
else
printf("no 2nd comparision is not equal\n");

*a = 15;

if (*a == i)
printf("yes 3rd comparision is equal\n");
else
printf("no 3rd comparision is not equal\n");

return 0;
}

关于无法理解静态变量的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12114341/

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