Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: scanf behavior in a for-loop

Tags:

c

for-loop

I came across the following code :

int i;
for(; scanf("%s", &i);)
    printf("hello");

As per my understanding, if we provide integer input scanf would be unsuccessful in reading and therefore return 0, thus the loop should not run even once. However, it runs infinitely by accepting all types of inputs as successful reads.

Would someone kindly explain this behaviour?

like image 650
nishantv Avatar asked Jan 26 '26 20:01

nishantv


1 Answers

That is the incorrect format specifier for an int: should be "%d".

It is attempting to read a string into an int variable, probably overwriting memory. As "%s" is specified, all inputs will be read thus scanf() returns a value greater than zero.

like image 93
hmjd Avatar answered Jan 28 '26 10:01

hmjd