ckd_add
|
定义于头文件
<stdckdint.h>
|
||
|
template
<
class
type1,
class
type2,
class
type3
>
bool ckd_add ( type1 * result, type2 a, type3 b ) ; |
(C++26 起) | |
计算加法 x + y 并将结果存储到 * result 中。该加法操作的处理方式如同两个操作数均以具有无限范围的带符号整数类型表示,然后将结果从此整数类型转换为 type1 。若赋值给 * result 的值正确表示该操作的数学结果,则返回 false ;否则返回 true 。此时赋值给 * result 的值为该操作的数学结果环绕至 * result 位宽后的值。
目录 |
参数
| a, b | - | 整数值 |
| result | - | 结果应存储的地址 |
返回值
如果赋给 * result 的值正确表示了加法运算的数学结果,则为 false ,否则为 true 。
注意
函数模板
ckd_add
具有与
C23
标准中指定的同名
泛型宏
相同的语义。
类型 type1 、 type2 和 type3 中的每一个都是无 cv 限定的有符号或无符号整数类型。
如果 type2 或 type3 不是合适的整数类型,或者如果 * result 不是合适整数类型的可修改左值,建议生成诊断信息。
示例
Compiler Explorer 预览 。
#include <cstdint> #include <limits> #include <print> #include <stdckdint.h> int main() { const std::uint8_t x{14}; std::uint16_t y{28}, result1{}; bool overflow{}; overflow = ckd_add(&result1, x, y); std::println("{} + {} => {} ({})", x, y, result1, overflow ? "Overflow" : "OK"); y = std::numeric_limits<std::uint16_t>::max(); overflow = ckd_add(&result1, x, y); std::println("{} + {} => {} ({})", x, y, result1, overflow ? "Overflow" : "OK"); std::uint32_t result2{}; overflow = ckd_add(&result2, x, y); std::println("{} + {} => {} ({})", x, y, result2, overflow ? "Overflow" : "OK"); }
可能的输出:
14 + 28 => 42 (OK) 14 + 65535 => 13 (Overflow) 14 + 65535 => 65549 (OK)
参考文献
- C++26 标准 (ISO/IEC 14882:2026):
-
- 29.11.2 受检整数运算
参见
|
(C++26)
|
对两个整数进行带检查的减法运算
(函数模板) |
|
(C++26)
|
对两个整数进行带检查的乘法运算
(函数模板) |
|
C 文档
关于
ckd_add
|
|