+ =和= + C赋值运算符有什么区别 [英] What is the difference between += and =+ C assignment operators
问题描述
我想知道 = +
和 + =
(以及其他赋值运算符)之间是否存在差异.我尝试过并且都做了同样的事情.那么有区别还是有约定?两者都能工作是因为我的编译器不检查标准字体吗?
I was wondering if there was a difference between =+
and +=
(and other assignment operators too). I tried and both did the same thing. So is there a difference or is there a convention? Do both work because my compilers dont check for standarts?
我犯了一个错误.在测试期间,我使用了错误的输入,导致我认为它们都在做相同的事情.原来他们是两回事.
I made a mistake. I used bad inputs during my testing which led me to thinking they are both doing the same thing. Turns out they are two different things.
+ =
运算符将右值添加到左值
+=
operator adds rvalue to lvalue
x += y;
x = x + y;
= +
只需将分配给左值
x =+ y;
x = +y;
x = y;
推荐答案
在现代C甚至是中古的C语言中, + =
是复合赋值运算符,而 = +
被解析为两个单独的标记. =
和 +
.标点符号允许相邻.
In modern C, or even moderately ancient C, +=
is a compound assignment operator, and =+
is parsed as two separate tokens. =
and +
. Punctuation tokens are allowed to be adjacent.
所以,如果您写:
x += y;
等效于
x = x + y;
除了 x
仅被评估一次(如果它是一个更复杂的表达式,这可能很重要).
except that x
is only evaluated once (which can matter if it's a more complicated expression).
如果您写:
x =+ y;
然后将其解析为
x = + y;
和 +
是一元加号运算符.
非常的C早期版本(大约1970年代中期,1978年K& R1出版之前)使用了不同的符号进行化合物赋值.在现代C使用 + =
的地方,早期C使用 = +
.早期的C没有一元 +
运算符,但确实有一元-
运算符,并且使用 =-
会引起问题.程序员会写 x = -y
的意思是 x = -y
,但是它被默默地解释为 x =-y
.为了避免该问题,在1975年至1978年之间对语言进行了更改.直到1999年,我使用了一个编译器(VMS上的VAXC),该编译器会警告 =-
的使用模棱两可,但会使用较早的含义.除非您是一个业余爱好者,并且正在使用一些非常旧的软件和/或硬件,否则现在不必担心.
Very early versions of C (around the mid 1970s, before the publication of K&R1 in 1978) used different symbols for compound assignments. Where modern C uses +=
, early C used =+
. Early C had no unary +
operator, but it did have a unary -
operator, and the use of =-
caused problems; programmers would write x=-y
intending it to mean x = -y
, but it was silently interpreted as x =- y
. The language was changed some time between 1975 and 1978 to avoid that problem. As late as 1999, I worked with a compiler (VAXC on VMS) that would warn about an ambiguous use of =-
, but would use the older meaning. That shouldn't be a concern now unless you're a hobbyist playing with some very old software and/or hardware.
(A 1975 C参考手册显示了旧的 =-
, = +
等复合赋值运算符的形式,由Kernighan和Ritchie出版的第一版 C编程语言1978年,显示了现代的-=
, + =
等,但在时代性"下提到了较旧的形式.)
(A 1975 C Reference Manual shows the old =-
, =+
, et al forms of the compound assignment operators. The first edition of The C Programming Language by Kernighan and Ritchie, published in 1978, shows the modern -=
, +=
, et al, but mentions the older forms under "Anachronisms".)
这篇关于+ =和= + C赋值运算符有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!