ckd_mul - cppreference.com
From cppreference.com
template< class type1, class type2, class type3 > bool ckd_mul( type1* result, type2 a, type3 b ); |
(since C++26) | |
Computes the multiplication x × y and stores the result into *result. The multiplication 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 multiplication, true otherwise.
Note
The function template ckd_mul has the same semantics as the corresponding type-generic macro with the same name specified in C23.
Each of the types type1, type2, and type3 is a cv-unqualified signed or unsigned integer 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 <climits> #include <cstdint> #include <print> #include <stdckdint.h> int main() { uint8_t x; uint16_t y; uint16_t result_uint16; uint32_t result_uint32; bool overflow; x = 2; y = 21; overflow = ckd_mul(&result_uint16, x, y); std::println("{} * {} == {} ({})", x, y, result_uint16, overflow ? "Overflow" : "OK"); x = 2; y = UINT16_MAX; overflow = ckd_mul(&result_uint16, x, y); std::println("{} * {} == {} ({})", x, y, result_uint16, overflow ? "Overflow" : "OK"); x = 2; y = UINT16_MAX; overflow = ckd_mul(&result_uint32, x, y); std::println("{} * {} == {} ({})", x, y, result_uint32, overflow ? "Overflow" : "OK"); }
Output:
2 * 21 == 42 (OK) 2 * 65535 == 65534 (Overflow) 2 * 65535 == 131070 (OK)
References
- C++26 standard (ISO/IEC 14882:2026):
- 29.11.2 Checked integer operations