在非常容易的if语句中解决逻辑问题

时间:2017-08-14 14:13:52

标签: c++ if-statement

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

{
    "subject": "output_value",
    "version": 2,
    "id": 4,
    "schema": {
                "type":"record",
                "name":"test",
                "fields":[
                           {"name":"name","type":"string"},
                           {"name":"cnt", "type":"long"}
                         ]
               }
}

为什么“危险”被写入屏幕?我以为发现= 0,!发现不等于零。

3 个答案:

答案 0 :(得分:2)

您似乎正在以下列方式考虑if语句中的条件

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

但是在C ++中,if语句中的条件等同于

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

反过来相当于

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

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

答案 1 :(得分:1)

转换整数布尔值时,0false,其他任何内容为true

  1. found == 0 - found0
  2. (bool)found == false - 0被解释为false
  3. !found == true - not falsetrue
  4. (!found || anything else) == true - 如果or的前半部分为true,则整个表达式为true
  5. if (!found || anything else) { // always hit! }
  6. 请注意,布尔表达式||&&具有短路。因此,如果确定整个表达式的值是我的第一个子表达式,那么第二个子表达式甚至不是评估:

    • true || who cares
    • false && who cares

    语言 - 律师业:

      

    5.3.1一元运算符[expr.unary.op]

         

    ...

         

    9逻辑否定运算符!的操作数在上下文中转换为bool(第4条);如果转换后的操作数为true,则其值为false,否则为false。结果的类型为bool

答案 2 :(得分: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;
相关问题