[英]Why is x++-+-++x legal but x+++-+++x isn't?
I'm wondering why in C# the following is fine: 我想知道为什么在C#中以下是好的:
int y = x++-+-++x;
But 但
int y = x+++-+++x;
Isn't? 是不是? Why is there a bias against the +?
为什么对+有偏见?
The other two answers are correct; 另外两个答案是正确的; I will add to them that this illustrates some basic principles of lexical analysis:
我将补充一点,这说明了词法分析的一些基本原则:
These principles imply that +++x
will be lexed as ++ + x
and not + ++ x
. 这些原则意味着
+++x
将被定义为++ + x
而不是+ ++ x
。
The parser will then parse ++ + x
as ++(+x)
, and (+x)
is not a variable , it is a value , so it cannot be incremented. 解析器然后将
++ + x
解析为++(+x)
,而(+x)
不是变量 ,它是一个值 ,因此它不能递增。
See also: http://blogs.msdn.com/b/ericlippert/archive/2010/10/11/10070831.aspx 另见: http : //blogs.msdn.com/b/ericlippert/archive/2010/10/11/10070831.aspx
I'm using VS 2012. This is kind of interesting. 我正在使用VS 2012.这很有趣。
The first one can be parsed into: 第一个可以解析为:
int y = (x++) - (+(-(++x)));
without changing the end result. 而不改变最终结果。 So you can see why it would be valid.
所以你可以看出为什么它会有效。
The second one, however, has an issue with the +++x
because (I'm guessing) it sees the two ++ and tries to apply that unary operator to the r-value, which is another + (and not a valid r-value). 然而,第二个问题与
+++x
存在问题,因为(我猜)它看到了两个++,并尝试将该一元运算符应用于r值,这是另一个+(并且不是有效的) r值)。 You can group it in various ways to make it work, though: 您可以通过各种方式对其进行分组以使其正常工作:
int y = (x++)+(-(+(++x)));
is valid. 已验证。
I'm sure Jon Skeet or Eric Lippert or someone will show up and point out the relevant part of the C# spec. 我确定Jon Skeet或Eric Lippert或其他人会出现并指出C#规范的相关部分。 I'm not even sure where to start.
我甚至不确定从哪里开始。 But just following general left to right token parsing, you could see where it would choke on the second one.
但是,只需遵循一般的从左到右的令牌解析,您就可以看到它在第二个上会窒息。
The compiler is looking for a variable or property after the second ++
in int y = x+++-+++x
and can't determine that without a space or parentheses. 编译器在
int y = x+++-+++x
的第二个++
之后寻找变量或属性,并且如果没有空格或括号则无法确定。
You can do something like: 你可以这样做:
int y = x+++-+(++x);
or 要么
int y = x++ + -+ ++x;
if you wanted. 如果你想要的话。
The reason the first example you listed worked is because the compiler can determine that +-
from the ++x
; 你列出的第一个例子的原因是因为编译器可以从
++x
确定+-
; whereas in the second example it can't determine where to separate the +++
and naturally is expecting a variable after it reads the first ++
; 而在第二个例子中,它无法确定将
+++
分开的位置,并且在读取第一个++
后自然会期望变量; so in short, the compiler trying to use +x
as a variable, which is invalid. 所以简而言之,编译器试图使用
+x
作为变量,这是无效的。
Both are probably valid using some other compiler. 两者都可能使用其他一些编译器有效。 It depends on the semantics.
这取决于语义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.