On the usage of & and &&

Posted on 2008-03-21 23:27:51

A few weeks ago, I had a discussion with two colleagues about the use of “&” and “&&” in C#.

The first colleague asked the second whether the second argument of a boolean expression “a && b” would be evaluated if “a” was false. The second replied that “b” would not be evaluated if you used “&&”, but would if you used “&”.

My immediate reaction was: “eh? ‘&’ is a bitwise AND, and should not be used for booleans”. The second colleague reacted to that like: “eh? what’s a bitwise AND?”

After a short discussion in which MSDN was consulted, the second colleague proved to be right. If you think about it, a boolean is (conceptually) just an int of length 1, and if you do a bitwise AND between two ints of length 1, you get the desired result: true & true = true; false & true (or vice versa) = false; false & false = false.

Still, I think it’s corrupting the purpose of the bitwise AND to use it in exchange for the boolean AND: both arguments always need to be evaluated, while this is not the case for a boolean AND operation where the first operand is false. Still, one can wonder what would be faster…

After running both ways through the compiler and disassembler, the “&” compiles to shorter (IL) code, though that says nothing about speed. However, if one frequently has cases where the condition is of the following type, it’s not wise to use “&”:

if (false & some_really_long_computation()) {
    do_something();
}

Also, the same principle works for the “|” and “||” operators: bitwise OR and boolean OR. In checks for null, using the bitwise version wouldn’t even work as expected:

if (obj == null | obj.method() == value) {
   do_something();
}
// Throws a null pointer exception if obj is null

To prevent confusion and special cases, just use the boolean, lazy operators: && and ||.

Even then, more worrying is that the second colleague didn’t even know about bitwise ANDs. In my opinion, every programmer worth his salt should know at least a more “low-level” programming language than C#, preferably plain C, to really understand what s/he is doing. Today, it seems, there are more high level “scripters” than real programmers. Scripters who don’t have a clue about performance, just because what they throw together works fine on today’s powerful computers.

Posted in: Work