简体   繁体   中英

While loop in C, with non-executed condition

I keep coming across the following pattern in my C code:

_Bool executed = 0;
while (condition) {
   executed = 1;
   ...
}
if (!executed) {
   ...
}

Is there a better way to construct this?

Ideally:

while (condition) {
   executed = 1;
   ...
} else {
   ...
}

(A while / else loop, but not with Python's semantics. The else should be only executed if the while condition was immediately false.)

It seems

_Bool executed = 0;
while (condition) {
   executed = 1;
   ...
}
if (!executed) {
   ...
}

If condition has side effects, it can be changed with

if (condition) {
    do 
    {

    } while(condition);
} else {

}

But if you insist only using a while , and not a do... while then your penalty is evaluating condition again.

if (condition) {
    while(condition)
    {

    }
} else {

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM