#C 语言标准库函数 ckd_mul
/*********************************************
* @brief 计算整数乘法,并检查结果是否溢出
* @param[out] result 返回结果
* @param x 乘数
* @param y 乘数
* @return 是否溢出
********************************************/
bool ckd_mul(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 = 100000;
int b = 100000;
int result;
if (ckd_mul(&result, a, b)) {
printf("%d * %d = %d 结果溢出了!\n", a, b, result);
} else {
printf("%d * %d = %d\n", a, b, result);
}
return 0;
}
运行结果:
100000 * 100000 = 1410065408 结果溢出了!
#推荐阅读
#外部参考
#参考标准
- C23 standard (ISO/IEC 9899:2024):
- 7.20.1 The ckd_ checked integer operation macros (p: 311)