- What is the value of i2?
- Why doesn’t the line with i1 compile?
- How can you prevent this kind of errors?
1: static void Main(string args)
4: // The following line doesn't compile.
5: // int i1 = 2147483647 + 10;
7: // The following does compile
8: int ten = 10;
9: int i2 = 2147483647 + ten;
The value of i2 = –2147483639
i1 doesn’t compile because, when using const values, the compiler can check the expression at compile time. The compiler signals that the value of i1 will exceed the maximum allowed value for the type (in this case an int).
If you want to suppress this kind of messages and allow overflow to happen at compile time you can use the unchecked keyword.
int i1 = unchecked(2147483647 + 10); // (-2147483639)
The other way around, if you want to make sure that .NET checks for overflows at runtime you can use the checked keyword around a code block.