#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...
#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...
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.
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.
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. ;)
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!!