#if __GNUC__ >= 5 || __has_builtin(__builtin_add_overflow)
/** assume clang and gcc (>=5) to only have builtins for now. */
# define add_of(a, b, r) __builtin_add_overflow(a, b, r)
# define sub_of(a, b, r) __builtin_sub_overflow(a, b, r)
# define mul_of(a, b, r) __builtin_mul_overflow(a, b, r)
# define of_attr
#else
/** else use these generics, note behaviour of these is not strictly defined. */
# define add_of(a, b, r) ((*(r) = ((a) + (b))) < (a))
# define sub_of(a, b, r) ((*(r) = ((a) - (b))) > (a))
# define mul_of(a, b, r) (((*(r) = ((a) * (b))) || *(r) == 0) && ((a) != 0 && (b) > *(r) / (a)))
# if __clang__
# define of_attr __attribute__((optnone)) // Do not optimize above checks, in most systems this will work, but not defined.
# warning "Using non compiler builtins for overflow checks, this will be undefined for signed integers"
# elif __GNUC__
# define of_attr __attribute__((optimize("wrapv"))) // in older GCC we can make this behavior defined
# else
# warning "Using non compiler builtins for overflow checks, this will be undefined for signed integers"
# endif
#endif
overflow.h/Gcc5
最新推荐文章于 2025-11-19 08:30:00 发布
本文介绍了一种使用编译器内置函数或通用方法来检测整数运算溢出的技术。对于支持的编译器如Clang和GCC,利用__builtin_add_overflow等内置函数可以直接进行溢出检查。对于不支持内置函数的编译器,则提供了通用实现方式。

2274

被折叠的 条评论
为什么被折叠?



