C++ 中不等式 != 的运算符交换性

发布于 2024-09-12 04:43:53 字数 214 浏览 7 评论 0原文

我对以下表达式有一个简单的问题:

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

"(0 != a_variable)" 和 "(a_variable != 0)" 之间有什么区别? 我现在没有任何错误,但是这是错误的使用方式吗?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

阿楠 2024-09-19 04:43:53

如果您忘记了 !,第一个将给出错误 (0 = a_variable),第二个将造成严重破坏 (a_variable = 0)

此外,使用用户定义的运算符,第二种形式可以使用成员函数来实现,而第一种形式只能是非成员(可能是友元)函数。尽管这是一个非常糟糕的主意,但以不同的方式定义这两种形式是可能的。当然,由于 a_variable 是一个 int,因此在此示例中没有有效的用户定义运算符。

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.

一生独一 2024-09-19 04:43:53

0 != xx != 0 之间没有区别。

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

明媚殇 2024-09-19 04:43:53

它可能产生的任何区别是参数的计算顺序。 a != b 通常会评估 a,然后评估 b 并比较它们,而 b != a 会反之亦然。但是,我听说在某些情况下评估顺序是不确定的。

它对变量或数字没有太大影响(除非变量是带有重载 != 运算符的类),但当您比较某些函数调用的结果时,它可能会产生影响。

假设

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

操作数是从左到右计算的,那么调用 (f() != g()) 将产生 false,因为 f() code> 将评估为 -1 并将 g() 评估为 -1 - 而 (g() != f()) 将产生 true,因为 g() 将计算为 1f() - 到<代码>-1。

这只是一个例子 - 最好避免在现实生活中编写这样的代码!

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!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文