Saturday, February 28, 2009

In C are you a Righty or Lefty?

Do you write your code, like almost everyone does, like this (Those are Zeros if you have a funky font):
if( x == 0 ){...}
or do you do it correctly and do it this way?:
if( 0 == x ){...}
Why is the latter the correct way? It prevents you from making this mistake:
if( x = 0 ){...}
"Unless Debugging is an Obsession" put the constants on the left in any conditional test. Also use a lot of parentheses, you can never have to many parentheses, if there is more than one condition in the test. When you put the condition on the left, the compiler will refuse to compile the code at all, because you can not assign a value to a constant. Putting the constants on the right may elicit a warning if you are using a good quality compiler, if your lucky. I've been giving out this advice for years. The responses have been interesting:
I've never made that mistake. I don't need such crutches. -- AVR GCC List It does not read right. -- Well known Compiler Guru, in private email.
What is wrong with reading it as "if Zero is equivalent to X"? Do you want to ship products on time and under budget, or do you want to write code in the way that everyone else does?

2 comments:

  1. I do it the correct way, but have received many comments in code reviews questioning the readability! I prefer to have bug free code. ;-) Thanks for showing me that someone else out there does this too.

    ReplyDelete
  2. Netrino's Embedded C Coding Standard http://www.netrino.com/Coding-Standard also forces this to be done correctly. Elimination of bugs is our goal too.

    ReplyDelete