Why I don't write '
if (NULL == foo)' in C code
One of the infamous trivial bugs in C code is accidentally writing
=' instead of '
==' in conditional expressions; you get assignment
instead of equality checking. One common piece of advice for avoiding
this is to reverse the order of the check, putting the constant first.
This way, if you accidentally write '
NULL = foo' instead of the
version, you'll get a compile time error.
I can't stand to write this version, because it looks wrong to me. I recently figured out why it looks so wrong: because it doesn't match my mental narrative of the code.
I write code by thinking 'if foo is NULL ...' and typing '
if (foo ==
NULL)', a pretty direct mapping. Similarly, if I am reading code I
scan the '
if (..)' and go to the narrative version. When I try to
reverse the condition the narrative comes to a jarring stall; I am
thinking 'if foo is NULL' but writing something that looks like 'if
NULL is foo'.
For me, the benefits of reversed conditionals just aren't worth putting up with code that looks wrong but isn't. (We already know that ugly code is confusing code.)
Comments on this page:Written on 21 November 2005.