I’ve a for loop which keeps incrementing an integer value till the loop completes. So if the limit n is a double variable and the incremented variable ‘i’ is an integer, i gets incremented beyond its limits.
double total = 0;
double number = hugetValue;
for (int i = 1; i <= number; i++)
{
total = total + i;
}
return total;
What happens to ‘i’ if it exceeds its capacity? How the value of i changes? Will i get a runtime error?
Similar to the behaviour in some implentations of C where an
intjust wraps around from INT_MAX to INT_MIN ( though it’s actually undefined behaviour according to the ISO standard), C# also wraps. Testing it in VS2008 with:will result in the message box appering.
If your
hugetValueis greater than the maximumintvalue, then your loop will run forever because of this.For example, if it’s
2147483648, just as you think you’re getting close to it, theintwraps around from2147483647back to-2147483648and the loop just keeps on going.