Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will this for loop run infinitely?

Tags:

c

for-loop

scanf

I have some experience with the c programming but sometimes the author of some books just pose such strange syntactical question which we will never use in actual programming and similar to that I stuck on one such question though the answer is given but I am not able to understand the answer.Here is the code below

int main
{
int i;
for(;scanf("%d",&i);printf("%d",i)){
     ;
    }
}

The question is how many times this for loop will run and the answer given is indefinite Can anyone explain how the loop will get executed

like image 367
Rohit Saluja Avatar asked Jun 02 '26 21:06

Rohit Saluja


1 Answers

scanf returns number of elements successfully read and in this case it will be 1 if it reads a integer and keeps printing it.

Let's say you pass a character here then scanf() fails and exits from a for loop

like image 106
Gopi Avatar answered Jun 04 '26 10:06

Gopi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!