检查溢出

基本类型 / 数字 / 整型

#include <stdckdint.h>

//不检查范围:无符号运算会回绕
unsigned char b1 = 200;
unsigned char b2 = 100;
unsigned char b3 = b1 + b2;
//b3 is 44 (300 - 256)

//有符号溢出(INT_MAX + 1)是未定义行为;
//C23 的 ckd_add 会检查,溢出时返回 true
int sum1;
bool overflow1 = ckd_add(&sum1, INT_MAX, 1);
//overflow1 为 true,同时 sum1 为 -2147483648(回绕后的值)

int sum2;
bool overflow2 = ckd_add(&sum2, 2, 3);
//overflow2 is false, sum2 is 5

//ckd_sub 和 ckd_mul 的用法相同
long long product;
bool overflow3 = ckd_mul(&product, LLONG_MAX, 2);
//overflow3 is true

printf("b3 is %d\n", b3);
printf("overflow1 is %s\n", overflow1 ? "true" : "false");
printf("sum1 is %d\n", sum1);
printf("overflow2 is %s\n", overflow2 ? "true" : "false");
printf("sum2 is %d\n", sum2);
printf("overflow3 is %s\n", overflow3 ? "true" : "false");