We know that in C language, the 'while' keyword is used to define a loop that works based on the conditions passed to the loop. Now, since the condition can have two values, true or false, the code inside the while block will be executed repeatedly if the condition is true and will not be executed if the condition is false.
Now, by passing parameters to the while loop, we can differentiate between while(1) and while(0), because while(1) is a loop where the condition is always considered true, so the code inside the block Repeat execution will begin. Furthermore, we can state that it is not 1 that is passed to the loop that makes the condition true, but if any non-zero integer is passed to the while loop, then it will be considered as the true condition and hence the code starts executing.
On the other hand, while(0) is a loop where the condition is always considered false, so the code inside the block never starts executing. Furthermore, we can state that, only 0 is passed to the loop to make the condition false, so if any other non-zero integer (can be negative) is passed to the while loop, then it will be considered as a true condition and hence the code starts executing.
The points discussed above can be demonstrated through the following examples.
while(1) example
#include using namespace std; main(){ int i = 0; cout << "Loop get started"; while(1){ cout << "The value of i: "; if(i == 10){ //when i is 10, then come out from loop break; } } cout << "Loop get ended" ; }
Loop get started 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 Loop gets ended
while(0) example
#include using namespace std; main(){ int i = 0; cout << "Loop get started"; while(0){ cout << "The value of i: "; if(i == 10){ //when i is 10, then come out from loop break; } } cout << "Loop get ended" ; }
Loop get started Loop get ended
The above is the detailed content of In C language, what is the difference between while(1) and while(0)?. For more information, please follow other related articles on the PHP Chinese website!