Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using builtin overflow functions with uint64_t types

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 ints, long ints, long long ints 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:

  1. 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".

  2. 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?

like image 664
Alexander Grass Avatar asked Sep 05 '25 03:09

Alexander Grass


1 Answers

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)
like image 168
chux - Reinstate Monica Avatar answered Sep 09 '25 02:09

chux - Reinstate Monica