1

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?

6
  • Presumably you mean integer overflow, not stack overflow. If a and b are integers and can be larger than 2^31 when summed, then you need a larger data type like int64 Commented Feb 22, 2021 at 23:41
  • 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 Commented Feb 22, 2021 at 23:43
  • @bennji_of_the_overflow didn't help, see my error message Commented Feb 22, 2021 at 23:43
  • @daniel "see my error message" - you mean the one on your screen that we can't see? We're not mind readers. Error messages belong in your question. Regardless, int c = a + (b-a)/2;, under the premise that b >= a holds water, will prevent the additive overflow of a+b. Commented Feb 22, 2021 at 23:45
  • @WhozCraig amazing! Commented Feb 22, 2021 at 23:50

3 Answers 3

3

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);
Sign up to request clarification or add additional context in comments.

Comments

1
  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

Comments

1

Just use int c=a+(b-a)/2; if both a and b are positive. Otherwise you can use above mentioned approaches

1 Comment

Welcome to Stackoverflow. I think the answer might be improved. Wİth explanation, formating etc. But still thanks for the useful answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.