Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 +?

like image 671
user1968525 Avatar asked Jul 11 '13 17:07

user1968525


3 Answers

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

like image 185
Eric Lippert Avatar answered Nov 08 '22 10:11

Eric Lippert


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.

like image 41
Tim Avatar answered Nov 08 '22 10:11

Tim


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.

like image 42
Kcvin Avatar answered Nov 08 '22 10:11

Kcvin