3

[I thought this would have been asked already, but I can't find an answer].

When writing an if statement, should the thing I'm comparing against come first or second? (I am specifically curious about both C / C++ and Java).

Does it matter, or is it just stylistic? (Convention seems to be "variable first, value second").

Consider the following code:

#include <iostream>

int main() {
    int x = 5;

    if ( 5 == x ) {
        std::cout << "X == 5, true." << std::endl;
    }
    if ( x == 5 ) {
        std::cout << "5 == X, true." << std::endl;
    }

    return 0;
}

which outputs:

X == 5, true.
5 == X, true.

so there doesn't appear to be any difference. Are there subtleties I'm missing?

simont
  • 68,704
  • 18
  • 117
  • 136

5 Answers5

10

These are called Yoda Conditions and to my knowledge the main idea is to guard against accidental assignment (i.e. you can't assign to literals).

Yes, worth mentioning that something like if (a = 5) where a is not a bool is not allowed in languages such as Java (though OK in C/C++), but as the Wikipedia article points out it is still possible to guard against unwanted behavior:

It can also solve some types of unsafe null behavior.

String myString = null;
if (myString.equals("foobar")) { /* ... */ }
// This causes a NullPointerException in Java

With Yoda Conditions:

String myString = null;
if ("foobar".equals(myString)) { /* ... */ }
// This is false, as expected
Nobilis
  • 7,310
  • 1
  • 33
  • 67
5

Putting the constant first (aka "Yoda style") prevents problems from a simple typo:

if (x = 5) // if (x == 5) was intended

...still compiles but does the wrong thing (though most current compilers will warn about the problem).

if (5 = x) // if (5 == x) was intended

...absolutely cannot compile on anything even approaching a properly functioning compiler.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
2

No, there is no difference. It doesn't matter. Do whatever you like. Personally I'd do:

x == 5

Because it reads better (or so I think). 5 == x just doesn't sound right. But again, personal opinion.

I think you'll find that most people do x == 5 because you are comparing x, rather than comparing 5.

BlackHatSamurai
  • 23,275
  • 22
  • 95
  • 156
1

Both are ok. But it is more accepted to do so when the parameter on left side. example:

if ( x == 5 )

Anyway. it doesn't matter, do whatever you pleased and feel more comfortable with.

-4

In most cases you'll find the common practice is to have the variable come first because the operator == means assignment and here you are assigning the value 5 so it only makes sense to have the variable come first.

Your if statement should then look like this:

    if ( 5 == x ) {
        std::cout << "X == 5, true." << std::endl;
    }
Novo
  • 201
  • 2
  • 9