#C 语言标准库函数 ckd_sub
/*********************************************
* @brief 计算整数减法,并检查结果是否溢出
* @param[out] result 返回结果
* @param x 被减数
* @param y 减数
* @return 是否溢出
********************************************/
bool ckd_sub(Type1* result, Type2 x, Type3 y);
说明
计算整数加法 *result = x - y
,并检查结果是否溢出。
在进行计算时,两个操作数 x
y
当作无限精度的有符号数进行计算,最后将结果转换为 Type1
赋值给 result
。
如果结果在 Type1
的范围之内,则返回 true
;如果结果超出了 Type1
的范围,则返回 false
。
参数类型 Type1
,Type2
,Type3
应当为整数类型,但不可以是 bool
,位精度整数(_BitInt(n)
),普通 char
或枚举类型。
参数
result
- 返回结果(整数)x
- 被减数(整数)y
- 减数(整数)
返回值
result
中返回的是否是准确结果(是否溢出)
#示例
#include <stdio.h>
#include <stdckdint.h>
int main(void) {
int a = 10;
int b = 20;
unsigned char result;
if (ckd_sub(&result, a, b)) {
printf("%d - %d = %d 结果溢出了!\n", a, b, result);
} else {
printf("%d - %d = %d\n", a, b, result);
}
return 0;
}
运行结果:
10 - 20 = 246 结果溢出了!
#推荐阅读
#外部参考
#参考标准
- C23 standard (ISO/IEC 9899:2024):
- 7.20.1 The ckd_ checked integer operation macros (p: 311)