Sashakt Pathak Sashakt Pathak - 1 month ago 17
C Question

Unexpected Infinite for loop

I am beginner in C and I was experimenting with

for
loop and I came across a infinite loop which should not be a infinite loop, can anyone help me understand why it is a infinite loop

void main()
{
int i;

for(i=1,printf("Initialization");i++ <=5,printf("\nCondition");printf("%d",i))

printf("\nInside the loop :");
}


while this is not a infinite loop

void main()
{
int i;

for(i=1,printf("Intialization");printf("\nCondition"),i++<= 5;printf("%d",i))

printf("\nInside the loop\n");
}

Answer

The reason is that your loop conditions (between two semicolons) look like this:

i++ <=5, printf("\nCondition") // First loop
printf("\nCondition"), i++<= 5 // Second loop

Both conditions are comma expressions, meaning that only the last part matters in terms of generating the value (both parts are good for their side effects, though).

In the first case, the overall condition result is what printf("\nCondition") returns. It always returns non-zero*, interpreted as "true", so the loop is infinite.

In the second case, the overall result is what i++<=5 returns, which starts off as "true", and becomes "false" after five iterations. That is when the second loop terminates.

* Specifically, printf returns the number of characters printed, so in your case that would be 10. This is not essential to understanding why the loop is infinite, though.

Comments