value range propagation for _bitwise_ OR

bearophile bearophileHUGS at lycos.com
Sat Apr 10 13:29:06 PDT 2010


Adam D. Ruppe:

> Oh no! Eyeballing again showed a problem.. I should have put parens in my asserts:
> a | b < f(a,b)   !=  (a|b) < f(a,b)

Bugs are gold nuggets! Yes, the precedence of bitwise operators is low, it's an error-prone thing, it's a part of C/C++/D that causes frequent bugs in programs written by everybody. I add extra parentheses when I use bitwise operators.

Unfortunately I don't see a simple way to remove this significant source of bugs from the D2 language.

When you switch on full warnings GCC warns you about few possible similar errors, suggesting to add parentheses to remove some ambiguity (for the eyes of the programmers).

This is a small example in C:

#include "stdio.h"
#include "stdlib.h"
int main() {
    int a = atoi("10");
    int b = atoi("20");
    int c = atoi("30");
    printf("%u\n", a|b <= c);
    return 0;
}

If you compile it with GCC (I am using gcc 4.4.1):

...>gcc -Wall test.c -o test
test.c: In function 'main':
test.c:9: warning: suggest parentheses around comparison in operand of '|'

You always use -Wall (and other warnings) when you write C code. So in this case the C language+compiler is able to catch a bug like yours :-)

Bye,
bearophile



More information about the Digitalmars-d mailing list