问题
Can anyone explain the usage of while(1)? I am a beginner in c++ & want to know when should I use while(1)? And how can I use it? Please give an example to explain. Thanks in advance.
回答1:
Well, for embedded bare metal code it's often written like this:
int main() {
while(1) {
handle_interrupts();
poll_sensors();
}
// If you come here some processor exception occurred
}
回答2:
When one wants to implement a loop that exits from some mid-point of the loop body, a typical implementation would be an "infinite" loop with a conditional break
(or return
, throw
etc.) somewhere in the middle of the loop's body.
How you express that "infinite" loop is a matter of your own preference. Some people would use
while (true) // same as while (1)
{
...
if (exit condition is true)
break;
...
}
Others would opt for
for (;;)
{
...
if (exit condition is true)
break;
...
}
I'd personally use
do
{
...
if (exit condition is true)
break;
...
} while (true);
Choose whatever looks best to you.
回答3:
This is a basic usuage of an infinite loop:
while(1)
{
// several examples:
// keep running my motor
// keep checking temprature
// keep broadcasting messages
// keep listening on a channel
// etc
}
You can use an infinite loop but exit it once it meets a certain condition. Example:
while(1)
{
// keep asking user to insert some string inputs
//..
//but if he enters "exit", "break" out of the loop
if(UserInput == "exit")
break;
}
Also know that the below are all considered the same:
while(1)
, while(1==1)
, while(true)
来源:https://stackoverflow.com/questions/37056975/what-is-the-usage-of-while1