Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) (messy and not remotely portable).

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?

like image 836
MD XF Avatar asked Feb 05 '23 10:02

MD XF


1 Answers

It can be done with using an additional variable. For example

int passed = 0;

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

if (passed)
{
    someFunction();
}
else
{
    someOtherFunction();
}

To stop GCC from showing warning: suggest parenthesis around assignment value, write each (passed = etc) as ((passed = etc)).

like image 127
Vlad from Moscow Avatar answered Feb 13 '23 09:02

Vlad from Moscow