views:

48

answers:

4

Hi, I have a quick question about the following expression:

int a_variable = 0;
if(0!=a_variable)
   a_variable=1;

what is the difference between "(0 != a_variable)" and "(a_variable != 0)" ? I dont have any errors for now but is this a wrong way to use it??

+2  A: 

if you forget the !, the first will give an error (0 = a_variable) and the second will wreak havoc (a_variable = 0).

Also, with user-defined operators the second form can be implemented with a member function while the first can only be a non-member (possibly friend) function. And it's possible, although a REALLY bad idea, to define the two forms in different ways. Of course since a_variable is an int then there are no user-defined operators in effect in this example.

Ben Voigt
+1 Beat me to it.
Jamie Wong
A: 

There is no difference between 0 != x and x != 0.

orangeoctopus
glowcoder
A: 

Nope, they are exactly the same (in all the languages I've used). But, the second case tends to be used more often, so it's more readable when you are working on a project with multiple people. It's more common because numerical literals are used on the right side of the operator during assignment, but when doing comparison, it makes no difference.

maksim
A: 

Any difference it may make is the order in which the arguments will be evaluated. a != b would conventionally evaluate a, then evaluate b and compare them, while b != a would do it the other way round. However, I heard somewhere that the order of evaluation is undefined in some cases.

It doesn't make a big difference with variables or numbers (unless the variable is a class with overloaded != operator), but it may make a difference when you're comparing results of some function calls.

Consider

int x = 1;
int f() {
  x = -1;
  return x;
}
int g() {
  return x;
}

Assuming the operands are evaluated from left to right, then calling (f() != g()) would yield false, because f() will evalute to -1 and g() to -1 - while (g() != f()) would yield true, because g() will evaluate to 1 and f() - to -1.

This is just an example - better avoid writing such code in real life!

kFYatek
That's an invalid assumption, C++ makes no promises about the order of evaluation of operands to comparison operators.
Ben Voigt
Yes, and I pointed that. I just wanted to point out that this may be a difference for such kind of functions.However, as far as I know, when operator `!=` is overloaded in class, then `a != b` expands to `a.operator!=(b)`, and then the left-hand operand must be evaluated first. Or am I wrong?
kFYatek
in `a.operator!=(b)`, both `a` and `b` are evaluated before `operator!=` is called, and there is no guarantee on whether `a` is evaluated before `b`, `b` before `a`, or the steps of each subexpression are intermingled.
Ben Voigt