Reputation:
In my C++ code I have:
int c=(a+b)/2;
I know for sure that the final result won't cause integer overflow but this isn't guaranteed for (a+b)
Here is my error message:
Line 20: Char 27: runtime error: signed integer overflow: 1063376696 + 2126753390 cannot be represented in type 'int' (solution.cpp) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:31:27
How can I solve this type of problem?
Upvotes: 1
Views: 2034
Reputation: 11
Just use int c=a+(b-a)/2; if both a and b are positive. Otherwise you can use above mentioned approaches
Upvotes: 1
Reputation: 7383
Use a standard library function which avoids overflow:
std::midpoint(a, b);
Cast to a larger type which can avoid overflow:
static_cast<int>((static_cast<std::int64_t>(a) + static_cast<std::int64_t>(b))/2);
Detect it with compiler-specific flags, e.g. -ftrapv
, or built-ins, e.g. __builtin_add_overflow
:
if (__builtin_add_overflow(a, b, &result))
throw std::out_of_range("overflow");
Perform the calculation in such a way as to avoid overflow (break it into cases and figure out what it takes to avoid overflow in each case):
using U = unsigned int;
return a>b ? a-(static_cast<U>(a)-b)/2 : a+(static_cast<U>(b)-a)/2;
Upvotes: 1
Reputation: 1852
You can do the operation with 64 bit ints and then cast back to 32 bits.
int c = int((std::int64_t(a) + std::int64_t(b)) / 2);
Upvotes: 3