Consider the following code…
double total = Int32.MaxValue;
total++;
int previousX = 0;
for (var x = 0; x <= total; x++)
{
if (x == Int32.MaxValue)
{
Console.WriteLine("Int32 max reached.");
}
if (x < 0)
{
Console.WriteLine("Counter now < 0.");
}
previousX = x;
}
It would appear that, if you use var with a for loop the default type inference is of an int.
Is this correct because if the counter goes past the maximum for an int 32, instead of overflowing the stack it resets itself back to zero and then counts down from zero.
Note: previousX allows you to set breakpoints and see what the previous value of the counter “x” was.
Does anyone know why this happens?
It seems possible to get into a bit of a pickle by using var for the counter of a for loop.
It is important to understand that the var keyword does not mean “variant” and does not indicate that the variable is loosely typed, or late-bound. It just means that the compiler determines and assigns the most appropriate type. As you have
var x=0it determines thatxis anintin order to match0.So yes it is correct functionality.
Because of the manner in which negative numbers are represented (twos compliment) as a number wraps over its maximum value it will appear to reset and count down from -1 onwards.
The increment on
x++doesn’t occur until that iteration of the loop has completed.