ckd_mul
来自 zh.cppreference.net
| 定义于头文件 <stdckdint.h>
|
||
#define ckd_mul( result, a, b ) /* implementation-defined */
// exposed interface:
bool ckd_mul( type1* result, type2 a, type3 b );
|
(自C23起) | |
计算乘法 x × y 并将结果存储到 *result。乘法的执行如同两个操作数均以具有无限范围的有符号整数类型表示,然后将结果从该整数类型转换到 type1。如果赋值给 *result 正确表示运算的数学结果,则返回 false。否则返回 true。在这种情况下,赋值给 *result 是运算的数学结果按照的宽度进行回绕后的值 *result。
参数
| a, b | - | 整数值 |
| 结果 | - | 存储结果位置的地址 |
返回值
false 如果赋值给 *result 正确表示乘法的数学结果,true 否则。
注意
两者 type2 和 type3 应为除“普通”char、bool、位精确整数类型或枚举类型外的任何整数类型,且它们可以相同。*result 应为除“普通”char、bool、位精确整数类型或枚举类型外的任何整数类型的可修改左值。
建议在以下情况产生诊断消息:如果 type2 或 type3 不是合适的整数类型,或如果 *result 不是合适整数类型的可修改左值。
示例
运行此代码
#include <limits.h>
#include <stdckdint.h>
#include <stdint.h>
#include <stdio.h>
const char* text(bool overflow) { return overflow ? "Overflow" : "OK"; }
int main()
{
uint8_t x;
uint16_t y;
uint16_t result_uint16;
uint32_t result_uint32;
bool overflow;
x = 2;
y = 21;
overflow = ckd_mul(&result_uint16, x, y);
printf("%u * %u => %u (%s)\n", x, y, result_uint16, text(overflow));
x = 2;
y = UINT16_MAX;
overflow = ckd_mul(&result_uint16, x, y);
printf("%u * %u => %u (%s)\n", x, y, result_uint16, text(overflow));
x = 2;
y = UINT16_MAX;
overflow = ckd_mul(&result_uint32, x, y);
printf("%u * %u => %u (%s)\n", x, y, result_uint32, text(overflow));
}
输出:
2 * 21 => 42 (OK)
2 * 65535 => 65534 (Overflow)
2 * 65535 => 131070 (OK)
参考文献
- C23标准(ISO/IEC 9899:2024):
- 7.20.1 ckd_检查整数运算宏(第311页)
另见
(C23) |
两个整数的检查加法运算 (泛型函数宏) |
(C23) |
两个整数的检查减法运算 (泛型函数宏) |
C++文档关于ckd_mul
| |