C++ 中不等式 != 的运算符交换性
我对以下表达式有一个简单的问题:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您忘记了
!
,第一个将给出错误(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 anint
then there are no user-defined operators in effect in this example.0 != x
和x != 0
之间没有区别。There is no difference between
0 != x
andx != 0
.它可能产生的任何区别是参数的计算顺序。
a != b
通常会评估a
,然后评估b
并比较它们,而b != a
会反之亦然。但是,我听说在某些情况下评估顺序是不确定的。它对变量或数字没有太大影响(除非变量是带有重载
!=
运算符的类),但当您比较某些函数调用的结果时,它可能会产生影响。假设
操作数是从左到右计算的,那么调用
(f() != g())
将产生false
,因为f()
code> 将评估为-1
并将g()
评估为-1
- 而(g() != f())
将产生true
,因为g()
将计算为1
和f()
- 到<代码>-1。这只是一个例子 - 最好避免在现实生活中编写这样的代码!
Any difference it may make is the order in which the arguments will be evaluated.
a != b
would conventionally evaluatea
, then evaluateb
and compare them, whileb != 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
Assuming the operands are evaluated from left to right, then calling
(f() != g())
would yieldfalse
, becausef()
will evalute to-1
andg()
to-1
- while(g() != f())
would yieldtrue
, becauseg()
will evaluate to1
andf()
- to-1
.This is just an example - better avoid writing such code in real life!