Click here to Skip to main content
15,882,209 members
Articles / Programming Languages / C
Tip/Trick

Intelligent comparison syntax

Rate me:
Please Sign up or sign in to vote.
4.27/5 (4 votes)
2 Mar 2010CPOL 10.7K   2   5
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)


Written By
Software Developer (Senior)
Switzerland Switzerland
Graduated at TU Darmstadt in Math & CS, with a heavy focus on CAD/CAM

Programming and designing applications in C++ in the areas AI, real-time programming, client-server applications and CAD/CAM since 1985.

Personal interests: AI, computer graphics, games, reading

Comments and Discussions

 
GeneralMy vote of 1 Pin
Yoldas Askan15-Sep-14 7:04
Yoldas Askan15-Sep-14 7:04 
GeneralMy vote of 5 Pin
Michael Haephrati20-Feb-13 6:06
professionalMichael Haephrati20-Feb-13 6:06 
GeneralRe: My vote of 5 Pin
Stefan_Lang20-Feb-13 22:05
Stefan_Lang20-Feb-13 22:05 
GeneralRe: My vote of 5 Pin
Michael Haephrati20-Feb-13 22:17
professionalMichael Haephrati20-Feb-13 22:17 
Questionvote of 1 - What is the problem? Pin
Stefan_Lang2-Mar-10 3:38
Stefan_Lang2-Mar-10 3:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.