lundi 2 janvier 2017

Catch-all for if-else in C

We all know that C has if statements, and parts of that family are the else if and else statements. The else by itself checks if none of the values succeeded, and if so, runs the proceeding code.

I was wondering if there's something like the opposite of an else that checks if all of the values succeeded instead of none of them.

Let's say I have this code:

if (someBool)
{
    someBit &= 3;
    someFunction();
}
else if (someOtherBool)
{
    someBit |= 3;
    someFunction();
}
else if (anotherBool)
{
    someBit ^= 3;
    someFunction();
}
else
{
    someOtherFunction();
}

Sure, I could shorten this with:

  • a goto (gee, wonder why I won't do that)
  • writing if (someBool || someOtherBool || anotherBool) (super messy).

I figured it'd be much easier to write something like this:

if (someBool)
    someBit &= 3;
else if (someOtherBool)
    someBit |= 3;
else if (anotherBool)
    someBit ^= 3;
all  // if all values succeed, run someFunction
    someFunction();
else
    someOtherFunction();

Does C have this capability?

Aucun commentaire:

Enregistrer un commentaire