ckd_sub — ckd_sub
ckd_sub — ckd_sub (체크드 뺄셈)
ckd_sub는 오버플로/언더플로를 검사하며 뺄셈을 수행하는 매크로/함수예요. 점검된 산술(checked arithmetic) 연산이에요.
결과를 첫 인자의 가리키는 위치에 저장하고, 오버플로(언더플로)가 발생하면 true를 반환해요.
출처: cppreference (호환 C 함수)
본문
ckd_sub는 <stdckdint.h>(C23)에서 제공되며, C++의 std::ckd_sub과도 연관돼요.
#include <cstdint>
#include <limits>
#include <stdckdint.h>
int main()
{
std::int16_t result1{};
const bool underflow1{ckd_sub(&result1, (std::int8_t)-2, (std::int16_t)1)};
// -2 - 1 => -3 (OK)
std::int16_t result2{};
const bool underflow2{
ckd_sub(&result2, (std::int8_t)-2, std::numeric_limits<std::int16_t>::max())
};
// 언더플로 발생
}
특징
bool반환: 오버플로/언더플로 발생 시true, 아니면false.- 결과는 첫 번째 인자가 가리키는 곳에 저장돼요.
- 부호 있는/부호 없는 정수 모두 지원해요.
- 일반
-연산과 달리 오버플로가 UB가 아니라 검사 가능한 결과가 돼요.
std::int32_t result;
bool under = std::ckd_sub(&result, std::numeric_limits<std::int32_t>::min(), 1);
// 언더플로 → true
점검된 뺄셈은 정수 오버플로/언더플로가 위험한 안전 코드에서 유용해요. C23의 <stdckdint.h>와 C++의 std::ckd_* 계열이 제공해요.