[英]How does `int sum = n + - + - + - + n` compile where `n` is an `int`?
This afternoon, I really don't know what I was doing with Operators and C. Eventually, I wrote some code which I was thinking wouldn't compile, But I don't know how it worked. 今天下午,我真的不知道我在操作员和C上做了什么。最后,我写了一些我认为无法编译的代码,但我不知道它是如何工作的。
The code is: 代码是:
#include <stdio.h>
int main()
{
int n=2;
int sum = n + - + - + - + n; /* This line */
printf("%d\n", sum);
return 0;
}
And the output is: 输出是:
0
0
I am completely confused how the code compiled and what is happening behind the scene. 我完全混淆了代码编译方式以及场景背后发生的事情。
How does the line int sum = n + - + - + - + n;
线如何
int sum = n + - + - + - + n;
work? 工作?
All but the first are just unary operators . 除了第一个之外的所有人都只是一元运营商 。
n + - + - + - + n
is equivalent to 相当于
n + (-(+(-(+(-(+n))))))
which is in turn simply equal to 这反过来简直等于
n + (-n)
after resolving all the unary operators. 在解决了所有一元运算符之后。
-n
is, of course, ordinary negation; -n
当然是普通的否定; +n
does essentially nothing (though it has the side effect of forcing integral promotion). +n
基本上没有任何东西(尽管它具有强制整体推广的副作用)。
int sum = n + - + - + - + n;
/* b u u u u u u */
/* Order: 7 6 5 4 3 2 1 */
is equivalent to: 相当于:
n + (-(+(-(+(-(+n))))));
or simply n + (-n)
或者只是
n + (-n)
Note that unary operators bind more tightly than binary operators in C opeartor precedance table
and associativity of unary operator +-
is from right to left while of binary +-
operators in from left to right. 请注意,一元运算符绑定比
C opeartor precedance table
二元运算符更紧密,并且一元运算符+-
关联性从右到左,而二元+-
运算符从左到右。
Both of +
and -
are also unary operators. +
和-
都是一元运算符。 The result of +n
is the (promoted) value of n
. 的结果
+n
是的(促进)值n
。 The result of -n
is the negative of (promoted) n
. -n
的结果是(提升的) n
的否定。
n + - + - + - + n;
is equivalent to: 相当于:
n + (-(+(-(+(-(+n))))))
which is basically n + (-n)
assuming no overflow happens. 假设没有发生溢出,这基本上是
n + (-n)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.