How the answer of this for loop is 5?

  • A+
Category:Languages

I was practicing my C skills online. And I got a question like:

What is the output of this program?

void main(){ int i; for(i=1;i++<=1;i++) i++; printf("%d",i); } 

The answer was 5. But I thought the for loop would execute endlessly. As the i will be incremented on each iteration and i will be never less than or equal to 1. how come 5 will be the output of this program?

 


This is explained by the sequence of events:

i = 1; // for init i++ <= 1 ? true // for condition, i evaluates as 1 but is made into i = 2 after the expression i++; // inside for body, makes i = 3 i++; // for increment, makes i = 4 i++ <= 1 ? false // for condition again, i evaluates as 4 but is made into i = 5 after the expression // condition is false, for loop ends, i = 5 

Perhaps you are forgetting that the for condition, although false, is still executed to verify that before the program decides the loop is terminated.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: