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.

Wouter de Kort works as a lead architect and consultant. He helps organizations stay on the cutting edge of software development. Wouter focuses on DevOps. He loves solving complex problems and helping other developers to grow. Wouter authored the book DevOps on the Microsoft stack and a couple of other books. Wouter is a Microsoft MVP and an ALM Ranger. You can find him on Twitter (@wouterdekort), on his blog at wouterdekort.com and at the various conferences where Wouter speaks.

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.