ckd_add — ckd_add
ckd_add — ckd_add (체크드 덧셈)
ckd_add는 오버플로를 검사하며 덧셈을 수행하는 매크로/함수예요. 점검된 산술(checked arithmetic) 연산이에요.
결과를 첫 인자의 가리키는 위치에 저장하고, 오버플로가 발생하면 true를 반환해요.
출처: cppreference (호환 C 함수)
본문
ckd_add는 <stdckdint.h>(C23)에서 제공되며, C++의 std::ckd_add와도 연관돼요.
#include <cstdint>
#include <limits>
#include <stdckdint.h>
int main()
{
const std::uint8_t x{14};
std::uint16_t y{28}, result1{};
bool overflow{};
overflow = ckd_add(&result1, x, y);
// 14 + 28 => 42 (OK)
y = std::numeric_limits<std::uint16_t>::max();
overflow = ckd_add(&result1, x, y);
// result1은 오버플로된 상태, overflow == true
}
특징
bool반환: 오버플로(또는 언더플로)가 발생하면true, 아니면false.- 결과는 첫 번째 인자가 가리키는 곳에 저장돼요.
- 부호 있는/부호 없는 정수 모두 지원하며,
int보다 작은 타입은 승격되어 처리돼요. - 일반
+연산과 달리 오버플로가 정의되지 않은 동작(UB)이 아니라 검사 가능한 결과가 돼요.
std::uint32_t result;
bool over = std::ckd_add(&result, 4000000000u, 1000u); // 오버플로
점검된 산술 연산은 안전(critical)한 코드에서 정수 오버플로를 안전하게 다루는 표준 방법이에요. C23 신규 헤더 <stdckdint.h>와 C++의 std::ckd_* 계열이 제공해요.