[英]Need for break in while loop
I am writing a loop whereby if a queue is not empty, the loop will run, and I was just wondering if there was a need to include a break
at the end of the loop. 我正在编写一个循环,如果队列不为空,则循环将运行,我只是想知道是否需要在循环末尾添加一个break
。 Essentially each loop should run for every single element in the queue until the queue is empty. 本质上,每个循环应针对队列中的每个单个元素运行,直到队列为空。
So which of the following should it be - I just don't know if there is a right thing to do. 所以应该是以下哪一项-我只是不知道是否有正确的事情要做。
while (1)
{
/*process message from incoming queue*/
if (!msgs_inc.empty())
{
/*categorise incoming message into global map of outgoing messages*/
msgInfo current_msg = incMsgClassification(msgs_inc.front());
msgs_inc.pop();
clients_msg[current_msg.destID][current_msg.priorityLevel].push(current_msg);
}
}
or 要么
while (1)
{
//Sleep(50000);
//cout << "success" << endl;
/*process message from incoming queue*/
if (!msgs_inc.empty())
{
/*categorise incoming message into global map of outgoing messages*/
msgInfo current_msg = incMsgClassification(msgs_inc.front());
msgs_inc.pop();
clients_msg[current_msg.destID][current_msg.priorityLevel].push(current_msg);
break;
}
}
What you want to do is more cleanly written as .. 您想要做的是更干净地写为..
while (!msgs_inc.empty()) // loop as long as queue still has elements
{
/*process message from incoming queue*/
/*categorise incoming message into global map of outgoing messages*/
msgInfo current_msg = incMsgClassification(msgs_inc.front());
msgs_inc.pop();
clients_msg[current_msg.destID][current_msg.priorityLevel].push(current_msg);
}
Or perhaps 也许
while(1) {//infinite loop
while (!msgs_inc.empty()) // loop as long as queue still has elements
{
/*process message from incoming queue*/
/*categorise incoming message into global map of outgoing messages*/
msgInfo current_msg = incMsgClassification(msgs_inc.front());
msgs_inc.pop();
clients_msg[current_msg.destID][current_msg.priorityLevel].push(current_msg);
}
}
This is more relevant if this function is running on a seperate thread, and is the only piece of code running on that thread. 如果此函数在单独的线程上运行,并且这是在该线程上运行的唯一代码段,则这更相关。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.