Why I don't write 'if (NULL == foo)' in C code

November 21, 2005

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.)

Written on 21 November 2005.
« Weekly spam summary on November 19th, 2005
How to fiddle with Firefox .jar files relatively easily »

Page tools: View Source, Add Comment.
Search:
Login: Password:
Atom Syndication: Recent Comments.

Last modified: Mon Nov 21 00:50:18 2005
This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.