Ad

While Loop In C, With Non-executed Condition

- 1 answer

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.)

Ad

Answer

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 {

}
Ad
source: stackoverflow.com
Ad