0

Sample 1

int a = Int32.MinValue;
int b = -a;
Console.WriteLine("a={0}",a);
Console.WriteLine("b={0}", b);

Result

a=-2147483648
b=-2147483648

Sample 2

int a = Int32.MinValue;
int b = a-1;
Console.WriteLine("a={0}",a);
Console.WriteLine("b={0}", b);

Result

a=-2147483648
b=2147483647

In two samples: why doesn't it throw overflow exception. When I tried these samples in java environment, I got same results. Is there anyone who can explain this situation?

5
  • 3
    This is not Java. Please use valid tags only. Commented Oct 21, 2014 at 11:11
  • Try wrapping the .Net code in a checked{} block? Commented Oct 21, 2014 at 11:11
  • He said he "tried these samples in java environment". Anyway he should add the Java code if he did, not just the C# code. Commented Oct 21, 2014 at 11:12
  • You'll get an overflow error if you put it into checked block: checked {int b = -a ...} Commented Oct 21, 2014 at 11:14
  • msdn.microsoft.com/en-us/library/h25wtyxf.aspx Commented Oct 21, 2014 at 11:15

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.