Namespaces
Variants

ckd_add

ja.cppreference.net より
< c | 数値
ヘッダ <stdckdint.h>
#define ckd_add( result, a, b ) /* implementation-defined */
// exposed interface:
bool ckd_add( type1* result, type2 a, type3 b );
(C23 以降) で定義されています。

加算 x + y を計算し、結果を *result に格納します。加算は、両方のオペランドが無限の範囲を持つ符号付き整数型で表現されているかのように行われ、その後、結果はこの整数型から type1 に変換されます。*result に代入された値が演算の数学的な結果を正しく表す場合、false を返します。そうでない場合、true を返します。この場合、*result に代入される値は、演算の数学的な結果を *result の幅にラップアラウンドしたものです。

引数

a, b - 整数値
result - 結果を格納するアドレス

戻り値

false *result に代入された値が加算の数学的な結果を正しく表す場合、true そうでない場合。

ノート

両方の type2 と type3 は、"プレーンな" char、bool、ビット精度整数型、または 列挙型 以外の任意の整数型である必要があり、同じ型にすることができます。*result は、"プレーンな" char、bool、ビット精度整数型、または列挙型以外の任意の整数型の変更可能な左辺値である必要があります。

type2 または type3 が適切な整数型ではない場合、または *result が適切な整数型の変更可能な左辺値ではない場合、診断メッセージを生成することが推奨されます。

例

#include <limits.h>
#include <stdckdint.h>
#include <stdint.h>
#include <stdio.h>

const char* text(bool overflow) { return overflow ? "Overflow" : "OK"; }

int main()
{
    uint8_t x;
    uint16_t y;
    uint16_t result_uint16;
    uint32_t result_uint32;
    bool overflow;

    x = 14;
    y = 28;
    overflow = ckd_add(&result_uint16, x, y);
    printf("%u + %u => %u (%s)\n", x, y, result_uint16, text(overflow));

    x = 14;
    y = UINT16_MAX;
    overflow = ckd_add(&result_uint16, x, y);
    printf("%u + %u => %u (%s)\n", x, y, result_uint16, text(overflow));

    x = 14;
    y = UINT16_MAX;
    overflow = ckd_add(&result_uint32, x, y);
    printf("%u + %u => %u (%s)\n", x, y, result_uint32, text(overflow));
}

出力:

14 + 28 => 42 (OK)
14 + 65535 => 13 (Overflow)
14 + 65535 => 65549 (OK)

参考文献

  • C23 規格 (ISO/IEC 9899:2024):
  • 7.20.1 The ckd_ checked integer operation macros (p: 311)

関連項目

二つの整数のチェック付き減算操作
(型総称関数マクロ)
二つの整数のチェック付き乗算操作
(型総称関数マクロ)