ckd_sub

来自cppreference.com
在标头 <stdckdint.h> 定义
template< class type1, class type2, class type3 >
bool ckd_sub( type1* result, type2 a, type3 b );
(C++26 起)

计算减法 x - y 并将结果存储于 *result。进行减法如同两个操作数都表示为具有无限范围的有符号整数类型,随后将结果从这个整数类型转换为 type1 一样。如果赋给 *result 的值正确表示运算的数学结果,就返回 false。否则返回 true。这种情况下,赋给 *result 的值是运算的数学结果根据 *result 的宽度回绕所得。

参数

a, b - 整数
result - 存储结果的地址

返回值

如果赋给 *result 的值正确表示减法的数学结果则为 false,否则为 true

注解

函数模板 ckd_subC23 中规定的相同名字的对应泛型宏具有相同语义。

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

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

示例

#include <cstdint>
#include <limits>
#include <print>
#include <stdckdint.h>

int main()
{
    int16_t result1{};
    constexpr std::int8_t x1{-2};
    constexpr std::int16_t y1{1};
    const bool underflow1{ckd_sub(&result1, x1, y1)};
    std::println("{} - {} == {} ({})", x1, y1, result1, underflow1 ? "下溢" : "OK");

    int16_t result2{};
    constexpr std::int8_t x2{-2};
    constexpr std::int16_t y2{std::numeric_limits<std::int16_t>::max()};
    const bool underflow2{ckd_sub(&result2, x2, y2)};
    std::println("{} - {} == {} ({})", x2, y2, result2, underflow2 ? "下溢" : "OK");

    int32_t result3{};
    constexpr std::int8_t x3{-2};
    constexpr std::int16_t y3{std::numeric_limits<std::int16_t>::max()};
    const bool underflow3{ckd_sub(&result3, x3, y3)};
    std::println("{} - {} == {} ({})", x3, y3, result3, underflow3 ? "下溢" : "OK");
}

输出:

-2 - 1 == -3 (OK)
-2 - 32767 == 32767 (下溢)
-2 - 32767 == -32769 (OK)

引用

  • C++26 标准(ISO/IEC 14882:2026):
  • 29.11.2 Checked integer operations

参阅

(C++26)
两个整数的带检查加法运算
(函数模板) [编辑]
(C++26)
两个整数的带检查乘法运算
(函数模板) [编辑]
ckd_sub 的 C 文档