I am currently writing a program which makes heavy use of the uint64_t
type, to enhance compatibility across platforms.
As it happens, there are a lot of possibilities for overflows in my program, so I want to use the built in overflow functions from gcc.
Unfortunately, they are only defined on int
s, long int
s, long long int
s and so on. The uintX_t
types guarantee to always be of size X bits, which is not the case for those types e.g. a long int
is not guaranteed to be 64 bit. This makes me think, that the builtin overflow functions can't be used here.
How to solve this issue now?
I have two approaches:
using the UINT64_MAX
constant from stdint.h
and make the overflow prediction myself. However, I am not a friend of "re-inventing the wheel".
using the e.g. __builtin_add_overflow_p
function to only check for the overflow. However, I am not 100% sure if they can be applied to uint64_t
.
What is the best way? Am I overseeing something obvious?
Using builtin overflow functions with
uint64_t
... to use the built in overflow functions from gcc.
To form your own builtin_uadd64_overflow()
, without "re-inventing the wheel", use _Generic
to steer function selection.
#define builtin_uadd64_overflow(a,b,r) _Generic(*(r), \
unsigned: __builtin_uadd_overflow, \
unsigned long: __builtin_uaddl_overflow, \
unsigned long long: __builtin_uaddll_overflow \
)(a,b,r)