Just When You Think You Know it All...
Well, okay. I don’t know it all. I’ve known for a long time that I don’t know it all. But have felt that I am pretty experienced in C.
Thus, it was a pleasant surprise when Mark Crowther, my supervisor, told me about a clever trick that can help reduce certain types of bugs in code.
I’ve seen this trick used a lot in various opensource projects, and have always wondered at the rationale behind it.
It has to do with accidentally performing an assignment when you meant to test an equality condition. For example, in C, if I wanted to see if a variable equalled the number 5, I could do:
if( variable == 5 ) do_something();
The problem is that if you forget one of the equals signs, the comparison becomes an assignment:
if( variable = 5 ) do_something();
Thus, a bug is introduced since
variable is set to 5, overwriting its original value. Also, the condition will always be true since 5 (in C, at least) is non-zero (and all non-zero values are true).
The trick I learned is that if you reverse the condition, the compiler will catch the attempted assignment (since you cannot assign to a constant). Thus:
if( 5 == variable ) do_something();
This does the expected thing, while:
if( 5 = variable ) do_something();
This will give a compile error (you can’t assign to a constant).
Admittedly, this won’t help you when you are comparing one variable to another, but it’s definately an improvement!