+ 1
Why this Loop in Our Code below is "INFINITE LOOP"?
#include <stdio.h> int main() { for(1; 2; 3) printf("Hello"); return 0; }
9 Answers
+ 3
Aman Kumar Sinha , Rudra
In c, that 3 for loop parts are optional. Meaning you can left it empty.. So
for(;;) {} is an infinite loop, also without any warnings. .
In Posted code for( 1; 2; 3 ) { .. } , the condition is (2) which truth value in boolean type is true. And which never changes so it's a infinite loop.
hope it helps..
edit:
you can check this code. read comments :
#include <stdio.h>
int main() {
printf("hi\n");
int i = 0;
for(;;){
printf("Hello %d ",i);
if(++i == 10)
break; // breaks loop when i=10
}
printf("\nHello %d\n",i);
for(i=0 ; 0 ; ){ // never runs, condition is false, note: i set to 0.
printf("Hello %d ",i);
if(++i == 10)
break;
}
printf("\nHello %d\n",i);
for(;11;){ // infinite loop
printf("Hello %d ",i);
// if(++i == 1000) break; //uncomment this to break loop.
}
return 0;
}
+ 4
Because didn't set the condition statement when the code terminates and you haven't write any update statement...
For Loop Contains three parts...
1. Initialization
2. Condition
3. Update
Ex : for(int i=1; i<=5; i++){
cout<<i<<endl;
}
Here
i=1 is initialization
i<=5 is condition when loop stops running
i++ updating the value of i;
I hope this will help you....
Keep Coding...
+ 3
Jayakrishna🇮🇳 I agree... awesome explanation
+ 2
Your loop condition is 2 which equalent boolean value is true.
And it always true. No changing..
+ 2
Aman Kumar Sinha Thanx Bro
+ 1
Because you have not set the termination condition for the for loop
+ 1
Jayakrishna🇮🇳 Thanx for Giving Best Explanation. But I have Doubt, What happen about 1 and 3 in Our For Loop which is Infinite?
+ 1
Rudra
See the warnings.. Those statements have no effect in code. It does nothing in code. You are not assigning to anything and not using those anyways, anysence. Why those are syntactically not errors is because those are valid tokens or statement by language........
0
I don't know