gpt4 book ai didi

c - 为什么 GCC 有时只在初始化之前检测变量的使用?

转载 作者:太空狗 更新时间:2023-10-29 16:53:13 24 4
gpt4 key购买 nike

<分区>

我正在阅读一本书中的一些代码,当我决定进行更改以查看 sec 的未初始化值在 while 语句之前是什么时:

#include<stdio.h>

#define S_TO_M 60

int main(void)
{
int sec,min,left;

printf("This program converts seconds to minutes and ");
printf("seconds. \n");
printf("Just enter the number of seconds. \n");
printf("Enter 0 to end the program. \n");
printf("sec = %d\n",sec);
while(sec > 0)
{
scanf("%d",&sec);
min = sec/S_TO_M;
left = sec % S_TO_M;
printf("%d sec is %d min, %d sec. \n",sec,min,left);
printf("Next input?\n");
}
printf("Bye!\n");

return 0;
}

这在 GCC 下编译没有警告,即使 sec 在那个时候未初始化,我得到一个 32767 的值:

$ gcc -Wall test.c
$ ./a.out
This program converts seconds to minutes and seconds.
Just enter the number of seconds.
Enter 0 to end the program.
sec = 32767

但是当我注释掉 while 语句时:

#include<stdio.h>

#define S_TO_M 60

int main(void)
{
int sec;
//min,left;

printf("This program converts seconds to minutes and ");
printf("seconds. \n");
printf("Just enter the number of seconds. \n");
printf("Enter 0 to end the program. \n");
printf("sec = %d\n",sec);
/*
while(sec > 0)
{
scanf("%d",&sec);
min = sec/S_TO_M;
left = sec % S_TO_M;
printf("%d sec is %d min, %d sec. \n",sec,min,left);
printf("Next input?\n");
}
*/
printf("Bye!\n");

return 0;
}

现在 GCC 发出警告并且 sec 最终为零:

$ gcc -Wall test.c
test.c: In function ‘main’:
test.c:12:8: warning: ‘sec’ is used uninitialized in this function[-Wuninitialized]
printf("sec = %d\n",sec);
^
$ ./a.out
This program converts seconds to mintutes and seconds.
Just enter the number of seconds.
Enter 0 to end the program.
sec = 0
Bye!

为什么第二次出现警告而不是第一次出现?

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