Namespaces
Variants

ckd_sub

From ja.cppreference.net
ヘッダーで定義 <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 - 結果の格納先アドレス

戻り値

false が代入された場合、 * result に減算の数学的な結果が正しく表現されていることを示し、 true が代入された場合はそれ以外の場合を示します。

注記

関数テンプレート ckd_sub は、 型総称マクロ として C23 で規定されている同名のマクロと同じセマンティクスを持ちます。

type1 、 type2 、および type3 の各型は、cv修飾されていない符号付きまたは符号なし整数型です。

type2 または type3 が適切な整数型でない場合、あるいは * 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 ? "Underflow" : "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 ? "Underflow" : "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 ? "Underflow" : "OK");
}

出力:

-2 - 1 == -3 (OK)
-2 - 32767 == 32767 (Underflow)
-2 - 32767 == -32769 (OK)

参考文献

  • C++26標準 (ISO/IEC 14882:2026):
  • 29.11.2 チェック済み整数演算

関連項目

(C++26)
2つの整数に対するチェック付き加算演算
(関数テンプレート)
(C++26)
2つの整数に対するチェック付き乗算演算
(関数テンプレート)