Search code examples
c#.netcompilationintjit

strange no error within C# application


I have a c# application in which i have this code :

 public static void Main()
        {
            int i = 2147483647;
            int j = i+1;
            Console.WriteLine(j);
            Console.ReadKey();
        }

The result is : -2147483648

I know that every integer must be < 2147483648. So

  • Why I don't have a compilation or runtime error? like in this exemple

img

  • What is the reason of the negative sign?

thanks


Solution

  • The compiler defaults to unchecked arithmetic; you have simply overflown and looped around, thanks to two's-complement storage.

    This fails at runtime:

    public static void Main()
    {
        int i = 2147483647;
        int j = checked((int)(i + 1)); // <==== note "checked"
        Console.WriteLine(j);
        Console.ReadKey();
    }
    

    This can also be enabled globally as a compiler-switch.