ckd_add
来自cppreference.com
| 在标头 <stdckdint.h> 定义
|
||
| |
(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 ? "溢出" : "OK");
y = std::numeric_limits<std::uint16_t>::max();
overflow = ckd_add(&result1, x, y);
std::println("{} + {} => {} ({})", x, y, result1, overflow ? "溢出" : "OK");
std::uint32_t result2{};
overflow = ckd_add(&result2, x, y);
std::println("{} + {} => {} ({})", x, y, result2, overflow ? "溢出" : "OK");
}
可能的输出:
14 + 28 => 42 (OK)
14 + 65535 => 13 (溢出)
14 + 65535 => 65549 (OK)
引用
- C++26 标准(ISO/IEC 14882:2026):
- 29.11.2 Checked integer operations
参阅
(C++26) |
两个整数的带检查减法运算 (函数模板) |
(C++26) |
两个整数的带检查乘法运算 (函数模板) |
ckd_add 的 C 文档
| |