dmd warning request: warn for bitwise OR in conditional

bearophile bearophileHUGS at lycos.com
Thu Jan 21 23:59:08 PST 2010


Ali:
> We've been bitten by the following bug recently in C code:
>      uint flag = 0x1;
>      uint flags;
> 
>      if (flags | flag) {
>          dout.writefln("oops");
>      }
> 
> The programmer intended &.
> It is (almost?) always an error to use | in a conditional.

Why do you think it's almost always an error?

I have seen more than one time a related bug in C code (once written by me and other times written by other people):
if (foo & bar) {...

instead of:
if (foo && bar) {...

To avoid this kind of bug you can disallow integers in conditionals (requiring something like a ! or == 0 to turn an integral value in a boolean) as Java (and partially Pascal), or you can remove the && || from the language and replace them with "and" and "or", so it becomes easy to tell them apart from bitwise operators. I like the second way.

Bye,
bearophile



More information about the Digitalmars-d mailing list