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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With