0

Is there any difference between the following two code snippets?

if(x==4)
{

}

and

if(4 == x)
{

}

If so is there any great impact in performance?

S.Frank Richarrd
  • 488
  • 1
  • 3
  • 15

2 Answers2

2

Can there be a difference? Yes; if one of the types involved in the comparison is user-defined, then the writer of that type can make their operator== overload not be commutative.

However, such code should be considered ill-behaved. Users expect equality testing to be commutative. And in C++20, it will be much easier to write a commutative equality test than a non-commutative one.

So while the compiler will not stop you, it is reasonably safe to assume that equality testing will be commutative.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
0

In the most common case (read: "should you not be using an overloaded operator == of yours that would make it different, and should the type of x be comparable to 4") these two snippets have similar performances: both terms are going to be evaluated and then compared.

However there are differences, at least in the approach. For example, should you write by accident:

int x = 2;

if(x = 4) // = instead of ==, typed by mistake
{
    stuff();
}

this will compile (you might have warnings, but no error), and at run time, this will put 4 into x at test time. As x won't be equal to zero, the content of the block will be executed: stuff() will be called. So there will be a bug as your intent was not to change x and not to have the content of the block executed.

But if you write this:

int x = 2;

if(4 = x) // = instead of ==, typed by mistake
{
    stuff();
}

this code will not compile as 4 is a rvalue that cannot be used at the left part of such an assignment.

Shlublu
  • 10,917
  • 4
  • 51
  • 70