Reputation: 71
I was looking at the below C code from a study site and wanted to confirm if the default value for an empty entry with scanf("%d", number ) is -1? . That is if 'number' is an 'empty entry' does it automatically get interpreted as -1?
How does the below code not run the first if statement (increment counter) in the 'do" section if the empty entry is not understood as a -1?
int main(void)
{
int number;
int max = -100000;
int counter = 0;
do {
scanf("%d",&number);
if(number != -1)
counter++;
if(number > max)
max = number;
}
while (number != -1);
if(counter)
printf("The largest number is %d \n",max);
else
printf("Hey, you haven't entered any number!");
return 0;
}
Upvotes: 2
Views: 727
Reputation: 44274
There is no such thing as a "default value" for scanf
. If scanf
fails, no assignment will be made to the pointed to object.
So the idea of the code is that the loop shall continue until the the user inputs a -1
.
The code lacks a check of the return value from scanf
, i.e. instead of just
scanf("%d",&number);
the code should be like
if (scanf("%d",&number) != 1)
{
// Invalid input
// Add error handling or just exit
exit(1);
}
Upvotes: 3