1

I built a simple applet code which has a unsupported function __builtin_add_overflow in my gcc version 4.6. Considering some reasons I don't want to update my gcc version. So what function in my gcc version could use to replace that function ?

Melvin Levett
  • 341
  • 2
  • 3
  • 11
  • duplicates: [How to check if overflow occured?](https://stackoverflow.com/q/7683685/995714), [How to check if A+B exceed long long? (both A and B is long long)](https://stackoverflow.com/q/15920639/995714), – phuclv Mar 06 '19 at 06:48
  • Possible duplicate of [Test for overflow in integer addition](https://stackoverflow.com/questions/3422709/test-for-overflow-in-integer-addition) – phuclv Mar 06 '19 at 06:48

2 Answers2

2

Overflow detection depends on the type of your vars.

If they are unsigned, it is sufficient to detect if the result is lower than one of its operand.

inline unsigned_overflow(unsigned a, unsigned b){
  return (a+b)<a;

If both are unsigned, oveflows can only happen if operands are of the same sign and the sign of the result will be different. So there is overflow if the sign of result is different from the sign of its two operands.

inline signed_overflow(int a, int b){
  unsigned ua=a, ub=b;
  return (int)(((ua^(ua+ub))&((ub^(ua+ub)))<0  ;
Alain Merigot
  • 10,667
  • 3
  • 18
  • 31
1

You need to write it on your own. If the arguments are unsigned, it is not too hard to do (just compare if the sum is smaller than one of the addends in the larger input type). The overflow check for signed integer arithmetic can be rather complex, particularly if all three integer types are different. There is a GCC extension that helps somewhat: conversion from unsigned to signed types does not trigger undefined behavior, but reduces the value according to two's complement arithmetic. So you can use this:

  unsigned x1 = x1;
  unsigned y1 = y1;
  bool overflow = (int) (((x + y) ^ x) & (x + y) ^ y))) < 0;

The book Hacker's Delight discusses such topics extensively.

Florian Weimer
  • 32,022
  • 3
  • 48
  • 92