ckd_add
| Defined in header <stdckdint.h>
|
||
#define ckd_add( result, a, b ) /* implementation-defined */
// exposed interface:
bool ckd_add( type1* result, type2 a, type3 b );
|
(since C23) | |
Computes the addition x + y and stores the result into *result. The addition is performed as if both operands were represented in a signed integer type with infinite range, and the result was then converted from this integer type to type1. If the value assigned to *result correctly represents the mathematical result of the operation, it returns false. Otherwise, it returns true. In this case, the value assigned to *result is the mathematical result of the operation wrapped around to the width of *result.
Parameters
| a, b | - | integer values |
| result | - | address of where result should be stored |
Return value
false if the value assigned to *result correctly represents the mathematical result of the addition, true otherwise.
Note
Both type2 and type3 shall be any integer type other than “plain” char, bool, a bit-precise integer type, or an enumerated type, and they can be the same. *result shall be a modifiable lvalue of any integer type other than “plain” char, bool, a bit-precise integer type, or an enumerated type.
It is recommended to produce a diagnostic message if type2 or type3 are not suitable integer types, or if *result is not a modifiable lvalue of a suitable integer type.
Example
#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));
}
Output:
14 + 28 => 42 (OK)
14 + 65535 => 13 (Overflow)
14 + 65535 => 65549 (OK)
References
- C23 standard (ISO/IEC 9899:2024):
- 7.20.1 The ckd_ checked integer operation macros (p: 311)
See also
(C23) |
checked subtraction operation on two integers (type-generic function macro) |
(C23) |
checked multiplication operation on two integers (type-generic function macro) |
C++ documentation for ckd_add
| |