在C中捕获if-else的全部内容

时间:2017-01-03 01:41:57

标签: c if-statement keyword

我们都知道C有if个语句,该系列的部分内容是else ifelse语句。 else本身检查是否没有值成功,如果是,则运行前面的代码。

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

假设我有这段代码:

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

当然,我可以用以下方式缩短这个:

  • a goto(哎呀,不知道我为什么不这样做)
  • if (someBool || someOtherBool || anotherBool)(凌乱而不是远程便携)。

我认为写这样的东西要容易得多:

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是否具备此功能?

3 个答案:

答案 0 :(得分:7)

可以使用其他变量来完成。例如

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

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

试试这个。

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