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 +?
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
.
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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With