Why Put the Constant Before the Variable in a Comparison

Why put the constant before the variable in a comparison?

It's a mechanism to avoid mistakes like this:

if ( var = NULL ) {
// ...
}

If you write it with the variable name on the right hand side the compiler will be able catch certain mistakes:

if ( NULL = var ) {  // not legal, won't compile
// ...
}

Of course this won't work if variable names appear on both sides of the equal sign and some people find this style unappealing.

Edit:

As Evan mentioned in the comments, any decent compiler will warn you about this if you enable warnings, for example, gcc -Wall will give you the following:

warning: suggest parentheses around assignment used as truth value

You should always enable warnings on your compiler, it is the cheapest way to find errors.

Lastly, as Mike B points out, this is a matter of style and doesn't affect the performance of the program.

Why if( constant == variable ) is preferred instead of if ( variable == constant )

Because that form makes it harder to introduce a bug by forgetting one of the equals signs. Imagine if you did this:

if (k = 5)

This was intended as a comparison, but it's now an assignment! What's worse, it is legal, and it will mess up your program in multiple ways (the value of k is changed, and the conditional always evaluates to true).

Contrast this with

if (5 = k)

This is not legal (you cannot assign to a literal) so the compiler will immediately flag it as an error.

That said, this style of writing code (assignments within conditionals) is not as prevalent today as it once was. Most modern compilers will flag this as a warning, so it's unlikely to go undetected. Personally I don't like the second form and since the compiler is there to help I don't use it.

Why Constant first in an if condition

This is called yoda syntax or yoda conditions.

It is used to help prevent accidental assignments.

If you forget an equals sign it will fail

if(false = $a) fails to compile

if($a = true) assigns the value of true to the variable $a and evaluates as true

The Wordpress Coding Standards mention this specifically:

if ( true == $the_force ) {
$victorious = you_will( $be );
}

When doing logical comparisons, always put the variable on the right
side, constants or literals on the left.

In the above example, if you omit an equals sign (admit it, it happens
even to the most seasoned of us), you’ll get a parse error, because
you can’t assign to a constant like true. If the statement were the
other way around ( $the_force = true ), the assignment would be
perfectly valid, returning 1, causing the if statement to evaluate to
true, and you could be chasing that bug for a while.

A little bizarre, it is, to read. Get used to it, you will.

What's the reasoning behind putting constants in 'if' statements first?

So that you don't mix comparison (==) with assignment (=).

As you know, you can't assign to a constant. If you try, the compiler will give you an error.

Basically, it's one of defensive programming techniques. To protect yourself from yourself.

Is CONSTANT.equals(VARIABLE) faster than VARIABLE.equals(CONSTANT)?

Interesting question. Here is the test I wrote:

public class EqualsTest {
public static String CONST = "const";
public void constEqVar(String var) {
CONST.equals(var);
}
public void varEqConst(String var) {
var.equals(CONST);
}
}

Then I compiled it using javac: javac EqualsTest.java and disassembled it using javap: javap -c EqualsTest.

Here is the relevant snippet of javap output:

public void constEqVar(java.lang.String);
Code:
0: getstatic #2; //Field CONST:Ljava/lang/String;
3: aload_1
4: invokevirtual #3; //Method java/lang/String.equals:(Ljava/lang/Object;)Z
7: pop
8: return

public void varEqConst(java.lang.String);
Code:
0: aload_1
1: getstatic #2; //Field CONST:Ljava/lang/String;
4: invokevirtual #3; //Method java/lang/String.equals:(Ljava/lang/Object;)Z
7: pop
8: return

As you can see the only difference between theses 2 methods is order of operations: getstatic and then aload_1 in first case and aload_1 + getstatic in second case.

Pretty obvious that the execution time should not depend on this order.

The only reason to prefer const.equals(var) rather than var.equals(const) is to avoid NullPointerException.

comparing a #define constant with a variable of same value does not equal (C language)

#define mypi1 3.14
float mypi2 = 3.14;

The first of those is a double type, the second is a double coerced into a float.

The expression mypi1==mypi2 will first convert the float back to a double before comparing (the idea is that, if one type is of lesser range/precision than the other, it's converted so that both types are identical).

Hence, if the if statement is failing, it's likely that you lose information in the double -> float -> double round-trip(a).

To be honest, unless you're using a great many floating point values (and storage space is a concern), you should probably just use double everywhere. If you do need float types, use that for both values:

#define mypi1 3.14f
float mypi2 = 3.14f;

Comparing two float variables will not involve any conversions.


(a) See, for example, the following complete program:

#include <stdio.h>
#define x 3.14
int main(void) {
float y = 3.14; // double -> float
double z = y; // -> double
printf("%.50f\n", x);
printf("%.50f\n", z);
}

In this, x is a double and z is a double that's gone through the round-trip conversion discussed above. The output shows the difference that can happen:

3.14000000000000012434497875801753252744674682617188
3.14000010490417480468750000000000000000000000000000

Why do some experienced programmers write comparisons with the value before the variable?

Yes, that's correct. It's to detect the typo of = instead of ==.

What is the difference between if(CONST==variable) or if(variable==CONST)?

The reason some people use method 2 is because you'll get a compiler error if you mistype a = in place of the ==.

However, you'll have people (like me) who will still use method 1 because they find it more readable and if there is an error, it will be detected during testing (or, in some cases, static analysis of the code).

C variable and constant value comparison not matching

The value 0xFF is a signed int value. C will promote the *p to an int when doing the comparison, so the first if statement is equivalent to:

if( -1 == 255 ) break;

which is of course false. By using (signed char)0xFF the statement is equivalent to:

if( -1 == -1 ) break;

which works as you expect. The key point here is that the comparison is done with int types instead of signed char types.



Related Topics



Leave a reply



Submit