ckd_mul — ckd_mul
ckd_mul — ckd_mul (체크드 곱셈)
ckd_mul는 오버플로를 검사하며 곱셈을 수행하는 매크로/함수예요. 점검된 산술(checked arithmetic) 연산이에요.
결과를 첫 인자의 가리키는 위치에 저장하고, 오버플로가 발생하면 true를 반환해요.
출처: cppreference (호환 C 함수)
본문
ckd_mul은 <stdckdint.h>(C23)에서 제공되며, C++의 std::ckd_mul과도 연관돼요.
#include <climits>
#include <cstdint>
#include <stdckdint.h>
int main()
{
std::uint16_t result_uint16;
bool overflow;
overflow = ckd_mul(&result_uint16, (std::uint8_t)2, (std::uint16_t)21);
// 2 * 21 => 42 (OK)
overflow = ckd_mul(&result_uint16, (std::uint8_t)2, UINT16_MAX);
// 오버플로, overflow == true
}
특징
bool반환: 오버플로(언더플로) 발생 시true, 아니면false.- 결과는 첫 번째 인자가 가리키는 곳에 저장돼요.
- 부호 있는/부호 없는 정수 모두 지원해요.
- 일반
*연산과 달리 오버플로가 UB가 아니라 검사 가능한 결과가 돼요.
std::uint32_t result;
bool over = std::ckd_mul(&result, 50000u, 50000u); // 오버플로 발생
점검된 곱셈은 정수 오버플로가 치명적인 결과를 낳는 안전 코드에서 유용해요. C23의 <stdckdint.h>와 C++의 std::ckd_* 계열이 제공해요.