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:
goto
(gee, wonder why I won't do that) 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?
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))
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With