Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gcc -Wparentheses warns for b=1; !a & b but not !a & 1

Tags:

c

gcc

Consider following short program:

int main() {
    int a = 5, b = 1, c;
    c = !a & b;
    c = !a & 1;

    return c;
}

Does anyone know why gcc gives a warning for b = 1; c = !a & b; but not for c = !a & 1;?

$gcc -Wall test.c
test.c: In function 'main':
test.c:3:9: warning: suggest parentheses around operand of '!' or change '&' to '&&' or '!' to '~' [-Wparentheses]
     c = !a & b;

My gcc version is 8.3.1 (I tried with one other version and the same thing happens).

I'm often surprised how 'smart' gcc is. And this one looks like a very easy problem to figure out. So why still a warning for the first one?

like image 541
hko Avatar asked Nov 25 '25 23:11

hko


1 Answers

This warning comes into play when you have logical operators and bitwise operators in the same expression, as you would typically want either one or the other but not both.

The reason you don't see the warning in this case:

c = !a & 1;

Is because 1 is a boolean value and so both & and && will have the same effect in this expression.

If the constant were any value other than 1 or 0 it triggers the warning.

like image 172
dbush Avatar answered Nov 28 '25 16:11

dbush



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!