user15251211
user15251211

Reputation:

C++ Preventing Int Overflow for addition?

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

Answers (3)

Vishnu Vardhan
Vishnu Vardhan

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

Jeff Garrett
Jeff Garrett

Reputation: 7383

  1. Use a standard library function which avoids overflow:

    std::midpoint(a, b);
    
  2. 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);
    
  3. 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");
    
  4. 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;
    

https://godbolt.org/z/T3rPdq

Upvotes: 1

Dean Johnson
Dean Johnson

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

Related Questions