Difference between while(1) and while(0) in C language

1

Prerequisite: while loop in C/C++

In most computer programming languages, a while loop is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. The boolean condition is either true or false

while(1)

It is an infinite loop which will run till a break statement is issued explicitly. Interestingly not while(1) but any integer which is non-zero will give the similar effect as while(1). Therefore, while(1), while(2) or while(-255), all will give infinite loop only.

while(1) or while(any non-zero integer)
{ 
    // loop runs infinitely
}

A simple usage of while(1) can be in the Client-Server program. In the program, the server runs in an infinite while loop to receive the packets sent form the clients.
But practically, it is not advisable to use while(1) in realworld because it increases the CPU usage and also blocks the code i.e one cannot come out from the while(1) until the program is closed manually.
while(1) can be used at a place where condition needs to be true always.

// C program to illustrate while(1)
int main() 
{
   int i = 0;
   while ( 1 ) 
   {  
      printf( "%d\n", ++i );
      if (i == 5)     
           break; // Used to come 
                  // out of loop
   }
   return 0;
}

Output:

1
2
3
4
5

while(0)

It is opposite of while(1). It means condition will always be false and thus code in while will never get executed.

while(0)
{ 
    // loop does not run
}
// C program to illustrate while(0)
int main()
{
  int i = 0;
  while ( 0 ) 
  {
    // This line will never get executed 
    printf( "%d\n", ++i );  
    if (i == 5)
      break;
  }
 return 0;
}

This article is contributed by Anshika Goyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Recommended Posts:



1 Average Difficulty : 1/5.0
Based on 3 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.