samedi 28 mars 2015

Why does GCC only sometimes detect the use of a variable before its initialization? [duplicate]




This question already has an answer here:




I was reading some code from a book, when I decided to make a change to see what the uninitialized value of sec would be before the while statement:



#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;
}


This compiles under GCC with no warnings, even though sec is uninitialized at that point, and I get a value of 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


But when I comment out the while statement:



#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;
}


Now GCC issues a warning and sec ends up being zero:



$ 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!


Why did the warning show up the second time but not the first time?




Aucun commentaire:

Enregistrer un commentaire