Why is x++-+-++x legal but x+++-+++x isn't?

混江龙づ霸主 提交于 2019-12-10 01:50:05

问题


I'm wondering why in C# the following is fine:

int y = x++-+-++x;

But

int y = x+++-+++x;

Isn't? Why is there a bias against the +?


回答1:


The other two answers are correct; I will add to them that this illustrates some basic principles of lexical analysis:

  • The lexical analyzer is short-sighted -- it has minimal "look-ahead"
  • The lexical analyzer is greedy -- it tries to make the longest token it can right now.
  • The lexical analyzer does not backtrack trying to find alternate solutions when one fails.

These principles imply that +++x will be lexed as ++ + x and not + ++ x.

The parser will then parse ++ + x as ++(+x), and (+x) is not a variable, it is a value, so it cannot be incremented.

See also: http://blogs.msdn.com/b/ericlippert/archive/2010/10/11/10070831.aspx




回答2:


I'm using VS 2012. This is kind of interesting.

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). 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. 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.




回答3:


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.

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; 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.

Both are probably valid using some other compiler. It depends on the semantics.



来源:https://stackoverflow.com/questions/17599848/why-is-x-x-legal-but-x-x-isnt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!