我们都知道 C 有 if
语句,该系列的一部分是 else if
和 else
语句。 else
本身检查是否没有任何值成功,如果成功,则运行后续代码。
我想知道是否有与 else
相反的东西检查是否 所有 值都成功而不是一个。
假设我有这段代码:
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有这个能力吗?
最佳答案
这可以通过使用附加变量来完成。例如
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))
.
关于C 语言中 if-else 的全部捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41435333/