【问题标题】:What condition is being checked by the if statement [duplicate]if语句正在检查什么条件[重复]
【发布时间】:2019-08-29 07:55:41
【问题描述】:

所以我正在查找有关 2D Haar 小波变换的代码。还有一个我很困惑的 if 语句。

所以部分代码如下所示:

unsigned char indexMask[4]; // the '4' here supposed to be a variable but I'm going to keep it simple here

for (int k = 0; k < 4; k++) {
indexMask[k] = 0;
}

for (int j = 1; j <= 5; j+=2) {
    if (indexMask[j/2]) {
        //some codes here
    }
}

我的困惑是,这里的 if 语句检查什么?这是我第一次看到这种结构的 if 语句,所以我有点困惑。 非常感谢

【问题讨论】:

    标签: c++


    【解决方案1】:

    来自cppreference(仅引用相关部分):

    if ( condition ) statement-true
    
    condition     -   expression which is contextually convertible to bool
    

    通俗地说:数字可以转换为bool0 转换为 false,其他所有内容都转换为 true

    因此,条件也可以写成

    if (indexMask[j/2] != 0) {
        //some codes here
    }
    

    【讨论】:

    • 感谢您的回答,不胜感激
    【解决方案2】:

    表达式indexMask[j / 2] 可以隐式转换truefalse。 (它是一个整数类型,如果为 0 将转换为 false,如果有任何其他值将转换为 true)。

    它比丑陋的更具可读性

    if (indexMask[j / 2] == true) 
    

    或其他不必要的长变体。另请注意,如果初始化是

    unsigned char indexMask[4] = {};
    

    那么你就不需要那个循环来将元素设置为 0。

    【讨论】:

    • 好吧,我会说if (indexMask[j / 2] != 0)
    • 有些人可能会用cond ? true : false而不是cond哭...
    • 好吧,你总是可以添加更多的混乱,if (((indexMask[j / 2] == true) == true) == true) 呢? :P
    • “操作员”!! :) !!indexMask[j / 2].
    • @Bathsheba 我最喜欢的混淆工具仍然是逗号操作符
    【解决方案3】:

    这里发生的是indexMask[j / 2]上下文转换为布尔值。所以基本上每个非 0 的 int 或 char 值都会根据上下文转换为true,而 0 将转换为false

    请注意,这是 C 程序员使用条件的方式,因为 C 没有布尔类型,他们使用整数来返回真/假值。

    还要注意,转换不是隐式,而是上下文转换,它们之间有很大的区别。但我不想解释它们,因为它很可能不在这个问题的范围内。

    【讨论】:

      猜你喜欢
      • 2017-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 2018-09-09
      相关资源
      最近更新 更多