TechQuiz Question 4: Overflow!

  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?

 

   1:  static void Main(string[] args)
   2:  {
   3:   
   4:      // The following line doesn't compile.
   5:      // int i1 = 2147483647 + 10;
   6:   
   7:      // The following does compile
   8:      int ten = 10;
   9:      int i2 = 2147483647 + ten;
  10:   
  11:      Console.WriteLine(i2);
  12:  }

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.

Share

Leave a Reply

Your email address will not be published. Required fields are marked *

Post comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.