我在C代码中不断遇到以下模式:
_Bool executed = 0;
while (condition) {
executed = 1;
...
}
if (!executed) {
...
}
有没有更好的方法来构造它?
理想情况:
while (condition) {
executed = 1;
...
} else {
...
}
(一个while
/ else
循环,但不具有Python的语义。else
仅在while条件立即为假时才应执行。)
答案 0 :(得分:4)
似乎
_Bool executed = 0;
while (condition) {
executed = 1;
...
}
if (!executed) {
...
}
如果condition
有副作用,可以用
if (condition) {
do
{
} while(condition);
} else {
}
但是,如果您坚持只使用while
,而不是do... while
,那么您的罚款将再次评估condition
。
if (condition) {
while(condition)
{
}
} else {
}