When scanf()
reads input it cannot convert according to the specification, it stops scanning and returns the number of successful conversions. In your case, the character remains in the standard input buffer and scanf()
returns 0
.
Your code has undefined behavior because scanf()
fails to convert the input as an integer, leaving u
uninitialized. Passing this uninitialized value to printf
has undefined behavior. In your case, a somewhat random value is printed, which may be different or not, but any other behavior is possible including a crash.
You must test the return value of scanf()
to check if the conversion was successful. Here is a modified version:
#include <stdio.h>
int main(void) {
int u, res;
res = scanf("%d", &u);
if (res == 1) {
/* conversion succeeded */
printf("%d\n", u);
} else
if (res == 0) {
/* conversion failed */
printf("input is not a valid number\n");
} else {
/* res must be EOF */
printf("premature end of file: no input given\n");
}
return 0;
}