Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

__builtin_add_overflow function supported in gcc 5 and above and what functions could replace it in gcc 4.6?

Ask Question duplicates: How to check if overflow occured? , How to check if A+B exceed long long? (both A and B is long long) , phuclv Mar 6, 2019 at 6:48

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  ;
                signed_overflow only works with -fwrapv. You need to perform the potentially overflowing additions in an unsigned type.
– Florian Weimer
                Mar 6, 2019 at 6:54
                Now the comparison is never true because unsigned values are not negative. If you want to use the ^/& hack, you really need that GCC extension.
– Florian Weimer
                Mar 6, 2019 at 19:07

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.

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.