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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In C#, the
inttype is mapped to theInt32type, which is always 32-bits, signed.Even if you use
short, it still won’t overflow becauseshort+shortreturns anintby default. If you cast thisinttoshort–(short)(x + y)– you’ll get an overflowed value. You won’t get an exception though. You can usecheckedbehavior to get an exception:You can find information about
checked(andunchecked) 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 usuallyunchecked, but I bet that in some compilers/configurations you’ll get an exception on the firstzassignment.)