So I have a task to check for overflow when adding two int32_t numbers. In case of overflow my function must return maximum or minimum number of int32_t, depending on the sign of overflow, but using constants like UINT32_MAX is restricted. How do I do that? Here's the code if it will help you:
#include "inttypes.h"
int32_t
satsum(int32_t v1, int32_t v2) {
int32_t res = 0;
if(__builtin_sadd_overflow(v1, v2, &res)) {
if (res < 0) {
return ?
}
return ?
} else {
res = v1 + v2;
return res;
}
}
The value of
INT32_MAX(maximum value ofint32_t) andINT32_MIN(minimum value ofint32_t) are defined in C specification, so you can write the values instead of using the constants.Quote from N1570 7.20.2.1 Limits of exact-width integer types:
Here is one point: 2N can be represented as
1<<N, but1<<31will cause overflow, so you should use((1<<30)-1)*2+1instead of1<<31.Also you should use
INT32_Cmacor to use literals ofint32_tinstead ofint.In conclusion, what you should use are:
int32_t:((INT32_C(1)<<30)-1)*2+1int32_t:-((INT32_C(1)<<30)-1)*2-2