Anthony - 1 year ago 149
C Question

# Unintentional infinite 'for' loop

I just started programming in C, and while practicing with for loops, I came up with the following piece of code:

#include <stdio.h>

int main()
{
int x;

for (x=0;x=10;x=x+1)

printf("%d\n",x);

return 0;

}

When I run the code, I fall into an infinite loop. In my C manual it says that the condition x =10 is always true, but I can't get my head around it. If I give the variable x a value of 0 at the beginning, should the for loop not even start, or when the value of x reaches 10, shouldn't the loop stop?

The condition part of your for loop is wrong. What you are doing is :

for (x = 0; x = 10; x = x +1) {
// Operations
}

The condition you have got here is x = 10 which is an affectation. So x = 10 will return 10, which also means true. Your for loop is equivalent to :

for (x = 0; true; x = x + 1) {
// Operations
}

This is why you have got an infinite loop, you should replace the affectation operator = by the comparason one with two equals sign ==. This means the for will loop while x is equals to 10.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download