c - Unintentional infinite 'for' loop -
i started programming in c, , while practicing loops, came following piece of code:
#include <stdio.h> int main() { int x; (x=0;x=10;x=x+1) printf("%d\n",x); return 0; }
when run code, fall infinite loop. in c manual says condition x =10 true, can't head around it. if give variable x value of 0 @ beginning, should loop not start, or when value of x reaches 10, shouldn't loop stop?
thanks in advance!
the condition part of for
loop wrong. doing :
for (x = 0; x = 10; x = x +1) { // operations }
the condition have got here x = 10
affectation. x = 10
return 10, means true
. for
loop equivalent :
for (x = 0; true; x = x + 1) { // operations }
this why have got infinite loop, should replace affectation operator =
comparason 1 2 equals sign ==
. means for
loop while x
equals 10.
edit : virgile mentioned in comments, second for
loop, x
go 0 int_max
, behavior undefined. so, code more :
for (x = 0; true; x = 10) { // operations }
Comments
Post a Comment