Disallowing object creation on heap
February 5, 2013
Print characters coming in one of the 2 strings (and not in both)
April 24, 2013

Which of the two comparison is better

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 Comments

  1. kishu says:

    nice

  2. Ayush Jain says:

    Can you please explain the working of Garbage Collector in Java ?

Leave a Reply to Anonymous Cancel reply

Your email address will not be published. Required fields are marked *