Search code examples
c#.netvisual-studiointinteger-overflow

Why doesn't this overflow?


Given this code:

int x = 20000;
int y = 20000;
int z = 40000;

// Why is it printing WTF? Isn't 40,000 > 32,767?
if ((x + y) == z) Console.WriteLine("WTF?");

And knowing an int can hold −32,768 to +32,767. Why doesn't this cause an overflow?


Solution

  • In C#, the int type is mapped to the Int32 type, which is always 32-bits, signed.

    Even if you use short, it still won't overflow because short + short returns an int by default. If you cast this int to short - (short)(x + y) - you'll get an overflowed value. You won't get an exception though. You can use checked behavior to get an exception:

    using System;
    
    namespace TestOverflow
    {
        class Program
        {
            static void Main(string[] args)
            {
                short x = 20000;
                short y = 20000;
                short z;
    
                Console.WriteLine("Overflowing with default behavior...");
                z = (short)(x + y);
                Console.WriteLine("Okay! Value is {0}. Press any key to overflow " +
                    "with 'checked' keyword.", z);
                Console.ReadKey(true);
    
                z = checked((short)(x + y));
            }
        }
    }
    

    You can find information about checked (and unchecked) on MSDN. It basically boils down to performance, because checking for overflow is a little bit slower than ignoring it (and that's why the default behavior is usually unchecked, but I bet that in some compilers/configurations you'll get an exception on the first z assignment.)