I'm new to C decided to learn it myself because of certain job requirements (knew some java before this). I hope I don't get downvoted for this question because I've searched everywhere about while loops in C, the usage of scanf() and variable assignments to see if I've missed anything but nothing explains why this code below runs even when the check on the variable status for the while loop is not true anymore. This program was taken from a text book but it doesn't explain why it works either it's just an example.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
long num;
long sum = 0L;
int status;
printf("Please enter an integer to be summed ");
printf("(q to quit): ");
status = scanf("%ld", &num);
while (status == 1) {
sum = sum + num;
printf("Please enter next integer (q to quit): ");
status = scanf("%ld", &num);
}
printf("Those integers sum to %ld.\n", sum);
return 0;
}
When I enter a number on the console (to be read as input by scanf) and from my understanding that number is clearly assigned to the variable status. The while loop however is checking each iteration if status == 1 so why when I enter a number to be read by scanf after the while loop starts and that gets assigned to status the loop keeps going? The status variable is clearly not 1 anymore at this point. However it does stop when I enter q as suggested by the printed sentence to enter q to quit.
I've considered that it's perhaps checking if the value you entered is an integer or long to begin with, and if it's neither of those (e.g. if the input is a char) break the loop. But the problem is I cannot find a confirmation or explanation for this anywhere, of why isn't the check for the while loop checking if status is that exact integer 1.
%1d-->%ldstatus. You read a number intonumand thenstatusis assigned the number of values read in thescanfcall. As long as you input any valid number,statuswill be 1statusvariable isn't one anymore? You say it's "Clearly not 1 anymore", but why shouldn't it still be one?statusfor the while loop is not "true" anymore.'? Try printing thestatusvalue just after thescanfto make sure.scanf. You probably never saw nor wrote code that stores the return value ofscanf(). This function has many quirks, it is widely misunderstood. Read the specification carefully and use wisely.