【问题标题】:Why is this evaluated to true为什么这被评估为真
【发布时间】:2020-04-03 01:31:50
【问题描述】:

谁能解释一下为什么这条线被评估为真?

false && (true) ? false : true

我的意思是,就我对布尔运算的了解,false && something 被评估为假。

此外,正如预测的那样,这将被评估为假:

true && (true) ? false : true

【问题讨论】:

    标签: php boolean conditional-operator


    【解决方案1】:

    ?: 的优先级低于&&(参见manual),因此您的表达式被评估为

    (false && (true)) ? false : true
    

    =>

     false ? false : true
    

    =>

     true
    

    这同样适用于你的第二个表达式,它被评估为

    (true && (true)) ? false : true
    

    =>

     true ? false : true
    

    =>

     false
    

    【讨论】:

      【解决方案2】:

      尼克的回答已经解释过了。但是,我认为当我们将三元运算符 (:?) 视为 if-else 运算的缩写形式时,它更容易理解。因此,

      false && (true) ? false : true

      语句同:

      if (false && (true)) {
          return false;
      } else {
          return true; // the if condition is false, so this will get executed.
      }
      

      由于if 中的条件是false,因此会执行else 块,因此返回true

      【讨论】:

        猜你喜欢
        • 2023-03-20
        • 1970-01-01
        • 2014-05-19
        • 2014-02-16
        • 2018-07-01
        • 2017-04-28
        • 1970-01-01
        • 1970-01-01
        • 2014-02-09
        相关资源
        最近更新 更多