1
#include<iostream>

using namespace std;

int main(){

  int x = 1967513926;
  int y = 1540383426;

  cout<<x+y;

return 0;
}

Sum of above two integers is 3507897352 < 2^32.So Why wrong answer? Please help...

cryptomanic
  • 5,986
  • 3
  • 18
  • 30
  • 1
    `cout << std::numeric_limits::max() << '\n';` You're going to find `3507897352` is significantly larger than the aforementioned result on your implementation. Then consider the difference between a signed, and unsigned `int`. – WhozCraig Jun 19 '15 at 09:01
  • 1
    possible duplicate of [C++ numbers add to a negative](http://stackoverflow.com/questions/18680362/c-numbers-add-to-a-negative) – stijn Jun 19 '15 at 09:03
  • Int is 32 bit and it is singned, so it has range from -2147483648 to 2147483648. – czeski Jun 19 '15 at 09:05
  • 1
    You're forgetting that it takes 1 bit from those 32 to indicate if it is negative or positive, so your maximum signed int is 2^31 (on most systems at least). – Neil Jun 19 '15 at 09:11
  • @czeski int's size is not necessarily 32 bits. And a 32-bit int's range is from -2147483648 to 2147483647, **not** to 2147483648 – phuclv Sep 23 '16 at 10:45

4 Answers4

7

An int is a signed type, so its maximum is 2^31 - 1 = 2147483647, not 2^32 - 1. So you do get an overflow in this case.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
4

The behaviour of your program is undefined as you are overflowing the int type:

Paragraph 5/4 of the C++11 Standard (regarding any expression in general):

If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behaviour is undefined. [...]

Check the limits of your arguments (std::numeric_limits is useful here), before attempting a sum.

Alternatively, you can use unsigned types: overflowing those is safe as the standard states they will wrap around to 0 once the largest value is reached.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
3

The limit of an int is 2.147.483.647

You're just overflowing it.

When you do (on an int) 2.147.483.647 + 1. This gives you –2147483648. ;)

Guillaume Munsch
  • 1,233
  • 17
  • 37
  • That is the limit of a `int` on **your** platform, which is 32-bit, but the C standard only mandates that it be at least 16 bits wide, so saying otherwise without qualification is misleading. – underscore_d Apr 13 '18 at 15:09
0

Deepak,

Please check the maximum limit which int provides, if your sum is going above it this will not work, you have to increase the length of your integer values.

you can try numeric_limits which can bring you the max size you are looking for.

Hope this helps!!

Cheers!!