TechQuiz Question 4: Overflow!

2012-04-23

  1. What is the value of i2?
  2. Why doesn’t the line with i1 compile?
  3. How can you prevent this kind of errors?
static void Main(string\[\] args)
{
     // The following line doesn't compile.
     // int i1 = 2147483647 + 10;

    // The following does compile
    int ten = 10;
    int i2 = 2147483647 + ten;
    Console.WriteLine(i2);
}

Answer

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.