Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How the answer of this for loop is 5?

Tags:

c

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?

like image 588
Noob Avatar asked Dec 08 '22 13:12

Noob


1 Answers

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.

like image 141
Havenard Avatar answered Dec 28 '22 09:12

Havenard