bearophile Wrote:

> 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

The difference between those two use cases is that (a & b) is commonly used to 
check if a bit has been set.  (a | b) yields the same result as (a || b) when 
used in a conditional.

Is there any valid use for (a | b) as a 'truth' value?

Daniel

Reply via email to