2017-08-14 65 views
-1

所以我无法弄清楚背后的逻辑这个if语句麻烦的逻辑非常简单的if语句

int found = 0, value = 5; 
if (!found || ‐‐value == 0) 
cout << "danger "; 
cout << "value = " << value << endl; 

为什么“危险”写到这里的屏幕很简单呢?我以为自从找到= 0,!找到的不等于零。

+1

因为'found'不等于'0'(或'FALSE',我会说)。 – LogicStuff

+4

答案在你的问题:“自找到= 0,!找到不等于零”,因此测试条件必须为真。 –

+0

这可能是短暂的cuircit混淆你?你会得到相同的'if(!found){cout <<“danger”; }'因为如果第一个操作数是真的,第二个没有被评估 – user463035818

回答

2

看来你正在考虑在if语句的条件通过以下方式

if ((!found == 0) || (‐‐value == 0)) 

然而,在C++中的if语句的条件相当于

if ((!found) || (‐‐value == 0)) 

,反过来相当于

if ((found == 0) || (‐‐value == 0)) 

因此,如果找到的确实等于0,那么这个子表达式(found == 0)就是真的,它是逻辑OR运算符的结果。

+0

从我的脑海里发疯Vlad!非常感谢我的思考过程,非常感谢。真的很感激它。 – SuchARush

+0

@SuchARush根本没有。欢迎您。:) –

0

可以分解测试语句转换成这是更接近编译器做什么逻辑:

if (!found || --value == 0) 
{ 
    cout << "danger"; 
} 

是由编译器的东西接近这个(扩展位为例如逻辑理解,因为大会实际上生成使用反向逻辑...)。

if (found == 0) // !found 
{ 
    cout << "danger"; // if this is executed, the next test is not ! 
} 
else if (--value == 0) 
{ 
    cout << "danger"; 
} 

编译器使用反向逻辑,所以它并没有产生两倍的cout << "danger"声明。

为:

if (found == 0) 
{ 
    goto print_danger; 
} 
else 
{ 
    -- value;  // this statement is never executed if (found == 0) 
    if (value != 0) 
    { 
     goto skip_print_danger; 
    } 
} 

print_danger: 
    cout << "danger"; 

skip_print_danger: 
cout << "value = " << value; 
+0

好的一面。谢谢 :) – SuchARush