Search code examples
cfor-loopinfinite-loop

Explain this for loop


int i; for ( i = 0; i = 3; i++ ) printf("Hello");

In this C code, the loop condition is "i = 3". What does this condition mean? And the loop runs infintely. Does that mean the condition is true?


Solution

  • Your test part in your for loop is i = 3 which is an assignment to the variable. After assignment it evaluates as the which has been assigned: 3 which is not 0 hence true in C. Then the condition of your for loop is always hence you have an infinite loop.

    If the condition was i == 3, it would be false at the first iteration of the loop. hence the code will never execute the body of the for block.

    If the condition was i < 3, it would be true until the i variable is incremented up to the 3 value. Hence the body of the for loop would execute 3 times