开发者

Operator commutativity for inequality != in C++

I have a quick question about the following e开发者_JAVA技巧xpression:

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??


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.


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


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜