Feb 062013
 

While comparing a variable with a constant (literal) in C/C++ language, which of the two ways of comparison should we use ?

    if( x == 2 ) ...

    if( ptr == NULL ) ...

Or

    if( 2 == x ) ...

    if( NULL == ptr ) ...

In the first comparison we are writing variable on the Left side of == and literal (constant) on right side. whereas, in the second form we are writing the literal (2, NULL, etc.) on the left side of ==.

Solution:

From performance point of view both forms of comparisons are exactly same.

But, programmers have a tendency of writing ‘=’ in place of ‘==’ by mistake. Unfortunately, C or C++ will not give any error in the below statement

    if( x = 2 )

And the condition will always be true, because it is assignment and not comparison. Result of below assignment

    x = 2;

is 2 (Final value assigned to the variable on left side), which is true (non-zero in C/C++ means true). Similarly, a pointer assignment

    ptr = NULL

is always false (NULL is pointer ZERO).

Many modern compilers give warning if we use assignment in a condition, but still, these errors are very hard to debug.

Hence, it is a general guidelines to use literal on the left side of equality (‘==‘) comparison, because if you accidentally put assignment (=) in place of equality(==), it will be flagged as an error  at compile time.

Compiler will be able to detect the error in below statement because we cannot assign to literals (constants)

    if( 2 = x )  // Compiler will give ERROR ...

C++  Note: In C++, things are more complicated if we are talking about comparing objects of user defined types with literals. It is too complicated to be put in this post, because we need to consider Operator Overloading (both inside the class and in the global namespace) and single argument constructors (which can convert a literal into an object of user-defined type).

  3 Responses to “Which of the two comparison is better”

Comments (3)
  1. Can you please explain the working of Garbage Collector in Java ?

  2. nice

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)