fadedbee
fadedbee

Reputation: 44739

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

Upvotes: 3

Views: 69

Answers (1)

Tony Tannous
Tony Tannous

Reputation: 14856

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 {

}

Upvotes: 4

Related Questions