Yesterday while debugging some code I eventually found the culprit line:
for (int i=0; i <- b; i++)
instead of:
for (int i=0; i <= b; i++)
Why does this compile? I could understand if it had been mistyped as:
for (int i=0; i <-b; i++)
Explaining the more abstract form, in cSharp there is no token '<-', but two tokens '<' and '-'.
When the lexical analyzer reads the characters it checks if the next character produces any tokens that it can recognize (look-ahead). If not, it passes to the parser the last token that it was able to identify and proceeds to the next token identification.
Step by step:
< -> Token identified. Wait for the next entry (look-ahead)<- -> Unidentified token, pass < to the parser and keep the -- -> Token identified. Wait for the next entry (look-ahead)-b -> Unidentified token, pass - to the parser and keep the bb -> Token identified. Wait for the next entry (look-ahead)b; -> Unidentified token, pass b to the parser and keep the; In the end the parser translates this as "i < (-b)".
Obviously it has a deeper and more detailed explanation of how the lexical analyzer and the parser work, but I think it is not necessary to explain to answer your question.
In the summary, it makes no difference whether the code was written as "i <- b" or "i <-b" or "i < - b", because for the lexical analyzer of cSharp, space does not matter "i<-B".
References:
White space does not define scope in C#, so your statement compiles.
for
(
int
i
=
0;
i
< -
b
;
i
++
)
would compile too, but you'd be a monster if you let it. The unary - operator, like any other, doesn't necessarily need to be next to its operand to be valid.
-, it's confusing, sorry.It is not. Have a look at this snippet:
using System;
public class Program{
public static void Main(){
int i=0, j=-5;
for(;i<-j;i++)
Console.WriteLine("i: {0}, j: {1}", i, j);
}
}
The end result would be:
i: 0, j: -5
i: 1, j: -5
i: 2, j: -5
i: 3, j: -5
i: 4, j: -5
Its simple math. -(-) is +. So -(j) = -(-5) = 5.
C#<= -> <-) which lead to a bug in the code and is wondering why compiler has not helped to prevent it.
intandi.i <- bequalsi < (-b). Is5 < -10? No. But5 < -(-10)? Yes.