https://gcc.gnu.org/bugzilla/show_bug.cgi?id=104948

--- Comment #8 from dagelf <coenraad at wish dot org.za> ---
Makes perfect sense now. && is "logical" in that it can only produce a bool,
which in C is an int and anything except 0 or 1 is evaluated to false at
compile time. 

There was a time when 'logical' and 'bitwise' were used interchangeably, based
on the fact that 'boolean operators' work on 'boolean logic'. 

This is what lead me here:

$ cat test.c
int f(int a) {
  if ((a && 12) == 12 ) 
     return 11;
  return 10;
}

$ gcc -c -O0 test.c && objdump -d test1.o
test1.o:     file format elf64-x86-64
Disassembly of section .text:
0000000000000000 <f>:
   0:   55                      push   %rbp
   1:   48 89 e5                mov    %rsp,%rbp
   4:   89 7d fc                mov    %edi,-0x4(%rbp)
   7:   b8 00 00 00 00          mov    $0xa,%eax
   c:   5d                      pop    %rbp
   d:   c3                      retq   

With a single `&` it works as expected. 

In my defence, when I last did a C course all boolean operators were bitwise. I
suddenly feel really old that even C has changed. Even the definition of
'logical' and 'bitwise' has changed. 

Apologies for not testing the obvious '-Wall'. 

Also apologies for just skimming over the output of icc, clang and msvc... I
just noticed that they include jumps where gcc didn't, so I was mistaken. 

The optimizations are impressive.

Still, searching for the issues logged here with '&&' in an evaluation, does
point to the fact that the error message could be improved. Might I recommend
'non-bitwise boolean' in the message instead of just 'boolean'. Or even better,
add '(did you mean bitwise AND & instead of &&) if that's present.

$ gcc -Wall -c -O0  test.c 
test1.c: In function ‘f’:
test1.c:5:22: warning: comparison of constant ‘12’ with boolean expression is
always false (Did you mean & instead of &&?) [-Wbool-compare] 

Compare to "warning: comparison of constant ‘12’ with non-bitwise boolean
expression is always false [-Wbool-compare]" might lead to less confusion.

When expecting the result of an '&&' evaluation to be a bitwise AND, this
distinction can make a world of difference and could've pointed at least me in
the right direction.

Reply via email to