C 编程:+= vs =+
我和我的教授正在就 C 语言中的 += 运算符进行一些辩论。他说 += 或 =+ 可以工作,但他不确定为什么 =+ 可以工作。
int main()
{
int i = 0, myArray[5] = {1,1,1,1,1};
while(i < 5)
{
myArray[i] += 3 + i;
printf("%d\n", myArray[i]);
i++;
}
system("pause");
}
输出将产生 4, 5, 6, 7, 8。将 += 运算符更改为 =+ 会产生相同的结果。然而 -= 的作用与 =- 不同(这很明显,因为它将 3 视为 3)。
那么 C 专家:
- 为什么这可以与 =+ 一起使用?
- C 编译器如何处理 =+ 与 +=?
My professor and I are engaging in a bit of a debate about the += operator in C. He says that += or =+ will work, but he is not certain why =+ works.
int main()
{
int i = 0, myArray[5] = {1,1,1,1,1};
while(i < 5)
{
myArray[i] += 3 + i;
printf("%d\n", myArray[i]);
i++;
}
system("pause");
}
The output will yield 4, 5, 6, 7, 8. Changing the += operator to =+ yields the same results. However -= does not do the same as =- (which is obvious as it treats the 3 as a 3).
So C gurus:
- Why does this work with =+?
- How does a C compiler treat =+ versus +=?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
他错了;
+=
与=+
完全不同。表达式
x =+ 3
被解析为x = (+3)
。在这里,
+
成为(相当无用的)一元+
运算符。 (与否定相反)使用一元否定运算符将表达式
x =- 3
解析为x = (-3)
。He is wrong;
+=
is completely different from=+
.The expression
x =+ 3
is parsed asx = (+3)
.Here,
+
becomes the (rather useless) unary+
operator. (the opposite of negation)The expression
x =- 3
is parsed asx = (-3)
, using the unary negation operator.您的教授正在记住 C 的古代版本,其中
=+
、=-
、=*
等实际上是这样做的与+=
、-=
、*=
等含义相同(我们所说的版本比通常称为“ K&R”在这里。版本 6 UNIX,如果没记错的话。)在 C 的当前版本中,它们并不意味着同一件事;相反,它们的含义不同。首先带有等号的版本将被解析,就好像等号和后面的内容之间有空格一样。这恰好会为
=-
和=+
生成一个有效的程序(尽管不是执行您期望的操作的程序),因为-
和+
可以用作一元运算符。=*
或=/
可以用来解决争论。a *= 3
会将a
乘以三,a /= 3
会将其除以三,但a =* 3
是一个语义错误(因为一元*
只能应用于指针),而a =/ 3
是一个语法错误(因为/ 不能用作一元运算符)。
Your professor is remembering ancient versions of C in which
=+
,=-
,=*
etc did in fact mean the same thing as+=
,-=
,*=
etc. (We're talking older than the version generally referred to as "K&R" here. Version 6 UNIX, if memory serves.)In current versions of C, they do not mean the same thing; the versions with the equals sign first will be parsed as if there was a space in between the equals and whatever comes after. This happens to produce a valid program (albeit not a program that does what you expect) for
=-
and=+
because-
and+
can be used as unary operators.=*
or=/
could be used to settle the argument.a *= 3
will multiplya
by three, anda /= 3
will divide it by three, buta =* 3
is a semantic error (because unary*
can only be applied to pointers) anda =/ 3
is a syntax error (because/
can not be used as an unary operator).代码
将产生
myArray[i] = myArray[i] + 3 + i;
而
产生
myArray[i] = 3 + i
这就是我得到的。
Code
will yield
myArray[i] = myArray[i] + 3 + i;
whereas
yields
myArray[i] = 3 + i
that's what I got.
+
和-
一样也是一元运算符。+
is also a unary operator as is-
.