布尔逻辑,If语句缩减

时间:2016-05-25 10:49:31

标签: c++ if-statement boolean-logic

可能是一个非常简单的问题,但我对哪些选项感兴趣。我有三个条件,每个条件都应该产生不同的输出

// special cases
if(!A && B)
     return -1;
if(A && !B)
     return 1;
if(!A && !B)
     return 0;

// general case
return someOtherFunction(x, y);

我可以归结为 -

if(!A) {
    if(!B)
        return 0;
     return -1;
}
if(A && !B)
    return 1;

return someOtherFunction(x, y);

我可以进一步简化吗?这是用C ++编写的,所以我只能使用特定于语言的运算符和函数(包括STL)等。

4 个答案:

答案 0 :(得分:5)

return (!A ? (!B ? 0 : -1) : (!B ? 1 : someOtherFunction(x, y)));

这是使用嵌套的ternary operator

答案 1 :(得分:4)

使用查找表:

int lookup[2][2] = {
    { 0, -1}
,   { 1,  100}
};
...
bool A, B;
A = ...
B = ...
...
int res = lookup[A][B];
// When A && B, call other function
return res != 100 ? res : someOtherFunction(a, b);

注意:如果AB 不是布尔值,请使用双重否定技巧将它们转换为逻辑值:

return lookup[!!A][!!B];

答案 2 :(得分:3)

有趣的是,案例if (A and B)未定义。

我会使用以下解决方案,因为boolean可以转换为整数。

return A - B;

编辑:原始问题已更改。在那种情况下,我会这样做:

if (!A or !B)
    return A - B;
return someOtherFunction(A, B);

答案 3 :(得分:3)

我建议你保留原样,以便程序员(可能是你)的可读性和理解。除非确实需要,否则不要进行必要的优化。在这种情况下,你没有任何真正的优势。

您可以做的一件事是将AB的结果存储到变量中(如果它们是函数调用)。

相关问题