C 语言中 if-else 的全部捕获

Catch-all for if-else in C

我们都知道 C 有 if 语句,该家族的一部分是 else ifelse 语句。 else 本身会检查 none 个值是否成功,如果成功,则运行后续代码。

我想知道是否有与 else 相反的东西检查 所有 值是否成功而不是 none 个。

假设我有这个代码:

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

当然,我可以通过以下方式缩短它:

我想写这样的东西会容易得多:

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

C有这个能力吗?

可以通过使用附加变量来完成。例如

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

试试这个。

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

太晚了,不过我也添加了自己的版本。

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