# Difference between while(1) and while(0) in C/C++

C++Server Side ProgrammingProgramming

Here we will see what are the differences between while(1) and while(0) in C or C++. The while is a loop of C or C++. Using this loop we can check one condition, and the statements inside the loop will be executed while the condition is true.

The while(1) or while(any non-zero value) is used for infinite loop. There is no condition for while. As 1 or any non-zero value is present, then the condition is always true. So what are present inside the loop that will be executed forever. To come out from this infinite loop, we have to use conditional statement and break statement.

## Example

#include<iostream>
using namespace std;
main(){
int i = 0;
cout << "Starting Loop" << endl;
while(1){
cout << "The value of i: " << ++i <<endl;
if(i == 10){ //when i is 10, then come out from loop
break;
}
}
cout << "Ending Loop" ;
}

## Output

Starting Loop
The value of i: 1
The value of i: 2
The value of i: 3
The value of i: 4
The value of i: 5
The value of i: 6
The value of i: 7
The value of i: 8
The value of i: 9
The value of i: 10
Ending Loop

Similarly the while(0) is treated as while with false condition. So this kind of loop is useless. It will never execute the inner statement as 0 is treated as false.

## Example

#include<iostream>
using namespace std;
main(){
int i = 0;
cout << "Starting Loop" << endl;
while(0){
cout << "The value of i: " << ++i <<endl;
if(i == 10){ //when i is 10, then come out from loop
break;
}
}
cout << "Ending Loop" ;
}

## Output

Starting Loop
Ending Loop
Published on 30-Apr-2019 16:17:47