当前位置: C语言 -- 标准库 -- <stdckdint.h> -- ckd_mul

ckd_mul宏


概要:
#include <stdckdint.h>
bool ckd_mul(type1 *result, type2 a, type3 b);

描述:

该泛型宏对参数a和参数b执行乘法运算,并将运算结果存入参数result指向的对象中。运算执行就好像两个操作数都是具有无限范围的有符号整数类型,然后将运算结果从这个整数类型转换为type1类型。

*result应为可修改左值(modifiable lvalue)。type2和type3可以是相同类型,也可以是不同类型。

type1、type2和type3应为整数类型,但以下整数类型除外:

-- 普通char类型(plain char)。

(注:普通char类型是既不存在signed类型说明符,也不存在unsigned类型说明符的char类型。)

-- bool类型。

-- 位精确整数类型(bit-precise integer type)。

-- 枚举类型。


参数:
type1 *result

参数为指向type1类型对象的指针。

type2 a

参数为type2类型对象。

type3 b

参数为type3类型对象。


返回值:

如果*result能正确表示运算结果,该泛型宏返回false;否则该泛型宏返回true,这种情况下赋值给*result的值是运算结果按*result的宽度进行绕回(wrap around)处理后得到的值。


范例:
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
/*宏ckd_mul范例*/

#include <limits.h>
#include <stdckdint.h>
#include <stdio.h>

int main(void)
{
  unsigned short a = USHRT_MAX;
  unsigned short b = 2;
  unsigned short c = 0;
  unsigned int d = 0;
  
  /*发生溢出,得到的是绕回处理后的值。*/
  if(ckd_mul(&c, a, b))
    printf("The value is %hu after wrapping around.\n", c);
  else  
    printf("The value is %hu without wrapping around.\n", c);
  
  /*不会发生溢出,得到的是正常的数学值。*/
  if(ckd_mul(&d, a, b))
    printf("The value is %u after wrapping around.\n", d);
  else  
    printf("The value is %u without wrapping around.\n", d);  
  
  return 0;
}

可能输出:

The value is 65534 after wrapping around.

The value is 131070 without wrapping around.

(注:编译时实现未支持<stdckdint.h>头文件。)


相关内容:
ckd_add 表示检查过的整数加操作的泛型宏。
ckd_sub 表示检查过的整数减操作的泛型宏。


主要参考资料:

1、ISO/IEC 9899:2024