简体   繁体   English

GCC不会通过位屏蔽警告0或1

[英]GCC doesn't warn about 0 or 1 with bit-masking

Following program working fine on GCC without any warning. 以下程序在GCC上运行正常,没有任何警告。

#include <stdio.h>

int func(unsigned int mask)
{
    return (!mask & 0) ? 1 : 0;  // No warning for 0 or 1
                    ^^
                    0 or 1
}

int main() {
        func(1);
        return 0;
}

In this program If I write 0 or 1 . 在这个程序中,如果我写01 GCC doesn't give any warning. GCC不发出任何警告。

But, If I write other number like 2 : 但是,如果我写其他数字如2

 return (!mask & 2) ? 1 : 0; // GCC gives warning

Then GCC give following warning. 然后,GCC发出以下警告。

 warning: suggest parentheses around operand of ‘!’ or change ‘&’ to ‘&&’ or ‘!’ to ‘~’ [-Wparentheses]
     return (!mask & 2) ? 1 : 0;

GCC warns about other number like 2 , which is good, but why doesn't it warn about 0 or 1 ? GCC警告其他数字,例如2 ,这很好,但是为什么不警告01呢?

 (!mask & 2)

here you're mixing bitwise operators with boolean ones. 在这里,您将按位运算符与布尔运算符混合在一起。 That doesn't matter with 0 or 1 since only handling the first bit (boolean operators turn expressions into 0 or 1), but with 2 the result is different if you put parentheses or not, hence the warning. 这与01无关紧要,因为仅处理第一位(布尔运算符将表达式转换为0或1),但对于2则无论是否加上括号,结果都不同,因此发出警告。

(another example here which proves that gcc tries hard not to issue warnings unneccessarily) (这里的另一个例子证明了gcc努力不发出不必要的警告)

Because your code is valid C code. 因为您的代码是有效的C代码。 And the warning is only a suggestion . 警告只是一个建议

BTW !mask (a logical not operation) is a boolean, so can only be 0 or 1. if you want a bitwise-not operation, use ~mask . BTW !mask (逻辑非运算)是一个布尔值,因此只能为0或1。如果要按位非运算,请使用~mask Look at the list of operators in C. 查看C 中的运算符列表

As Jean-François Fabre explains having 0 and 1 is licit and common (they are common bitmasks). 正如让·弗朗索瓦·法布尔(Jean-FrançoisFabre)所解释的,具有0和1是合法且常见的(它们是常见的位掩码)。

GCC is emitting (with gcc -Wall -Wextra ) some warnings (using heuristics), but it has to balance between the case of weird but valid code and the case of improbable code. GCC(使用gcc -Wall -Wextra )发出了一些警告(使用启发式方法),但是它必须在奇怪但有效的代码情况与不可能的代码情况之间取得平衡。 It tries to avoid emitting useless warnings. 它试图避免发出无用的警告。

You can extend GCC to give additional warnings if you wanted to. 如果需要,您可以扩展GCC以发出其他警告。 Just spend months to code your own GCC plugin providing those warnings. 只需花费几个月的时间编写您自己的提供这些警告的GCC插件即可

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM