ckd_add

来自cppreference.com
< cpp‎ | numeric
在标头 <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_addC23 中规定的相同名字的对应泛型宏具有相同语义。

类型 type1type2type3 均为无 cv 限定的有符号或无符号整数类型。

建议实现在 type2type3 不是适当整数类型,或当 *result 不是适当整数类型的可修改左值时给出诊断消息。

[编辑]示例

Compiler Explorer 预览

#include <cstdint>#include <limits>#include <print>#include <stdckdint.h>   int main(){conststd::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 文档
close