+ 1

Why this Loop in Our Code below is "INFINITE LOOP"?

#include <stdio.h> int main() { for(1; 2; 3) printf("Hello"); return 0; }

24th Aug 2022, 5:46 PM
Rudra
Rudra - avatar
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; }
24th Aug 2022, 6:59 PM
Jayakrishna 🇮🇳
+ 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...
24th Aug 2022, 6:31 PM
Aman Kumar Sinha
Aman Kumar Sinha - avatar
+ 3
Jayakrishna🇮🇳 I agree... awesome explanation
25th Aug 2022, 2:19 AM
Aman Kumar Sinha
Aman Kumar Sinha - avatar
+ 2
Your loop condition is 2 which equalent boolean value is true. And it always true. No changing..
24th Aug 2022, 5:52 PM
Jayakrishna 🇮🇳
+ 2
25th Aug 2022, 3:08 PM
Rudra
Rudra - avatar
+ 1
Because you have not set the termination condition for the for loop
24th Aug 2022, 5:59 PM
Mohd Aadil
Mohd Aadil - avatar
+ 1
Jayakrishna🇮🇳 Thanx for Giving Best Explanation. But I have Doubt, What happen about 1 and 3 in Our For Loop which is Infinite?
25th Aug 2022, 3:11 PM
Rudra
Rudra - avatar
+ 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........
25th Aug 2022, 3:19 PM
Jayakrishna 🇮🇳
0
I don't know
26th Aug 2022, 1:52 PM
HackerX
HackerX - avatar