Catch-all for if-else in C

We all know that C has expressions if, and parts of this family are operators else ifand else. elseBy itself, it checks to see if any of the values ​​succeeded, and if so, it runs the processing code.

I was wondering if there is something like the opposite elsethat checks if all values ​​have succeeded, and not one 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();
}

Of course, I could shorten this with:

  • a goto(yes, I wonder why I won’t do it)
  • record if (someBool || someOtherBool || anotherBool)(dirty and not remote portability).

I realized that it would 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 feature?

+4
3

.

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();
}

GCC warning: suggest parenthesis around assignment value, (passed = etc) ((passed = etc)).

+7

, .

return
someBool?      (someBit &= 3, someFunction()) :
someOtherBool? (someBit |= 3, someFunction()) :
anotherBool?   (someBit ^= 3, someFunction()) :
someOtherFunction();

(void(*)(void)
someBool?      (someBit &= 3, someFunction) :
someOtherBool? (someBit |= 3, someFunction) :
anotherBool?   (someBit ^= 3, someFunction) :
someOtherFunction
)();

void (*continuation)(void) =
someBool?      (someBit &= 3, someFunction) :
someOtherBool? (someBit |= 3, someFunction) :
anotherBool?   (someBit ^= 3, someFunction) :
someOtherFunction;
continuation();
+1

Try it.

int test=0;

if (someBool) {
    test++;
    someBit &= 3;
    someFunction();
}

if (someOtherBool) {
    test++;
    someBit |= 3;
    someFunction();
}

if (anotherBool) {
    test++;
    someBit ^= 3;
    someFunction();
}

if (test==0) {
    noneFunction();
} else if (test==3) {
    allFunction();
}
0
source

Source: https://habr.com/ru/post/1665570/


All Articles