Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C

Intelligent comparison syntax

4.27/5 (4 votes)
2 Mar 2010CPOL 1  
When you compare a variable (a lvalue) to a constant (not a lvalue), always write the lvalue on the right hand side of the comparison.Bad example:if ( n == 5 ){ // do something}Good example:if ( 5 == n ){ // do something}This will help with your debugging in case...
When you compare a variable (a lvalue) to a constant (not a lvalue), always write the lvalue on the right hand side of the comparison.

Bad example:
if ( n == 5 )
{
   // do something
}


Good example:
if ( 5 == n )
{
   // do something
}


This will help with your debugging in case of a typo: if you mistype '==' as '=', in the first case, your code will compile just fine, resulting in a program with some hard to catch error which might take you hours to find.

In the second case however your compiler will immediately complain, since the syntax is incorrect and you will find and fix the error within seconds.

(C) notice: Thanks to Ralf Babel for this invaluable tip he published in his book, "Das Amiga Guru Buch" (originally available in german only, but to my knowledge there is a much newer english version as well)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)