- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Difference between while(1) and while(0) in C/C++
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

Advertisements