In a recent discussion about a question on another Stack Exchange site, I was made aware that seemingly innocent arithmetic expressions of unsigned
integral types in C++ can easily invoke undefined behavior.
In a recent discussion about a question on another Stack Exchange site, I was made aware that seemingly innocent arithmetic expressions of unsigned
integral types in C++ can easily invoke undefined behavior.
tl;dr The purpose of the code is to allow writing
constexpr auto x = std::uint16_t { UINT16_MAX }; constexpr auto y = std::uint16_t { UINT16_MAX }; static_assert(multiply(x, y) == 1u, "broken math");
in a portable way that won't invoke undefined behavior. If that is enough for you to understand the problem at hand, you are welcome to skip the first two sections and jump straight to the section titled "Code for Review".
Otherwise, the section titled "Problem Statement" explains why simply writing x * y
would not have done the trick and the section "Proposed Solution" provides background information about the implementation of the multiply
function I'm asking review for.
tl;dr The purpose of the code is to allow writing
constexpr auto x = std::uint16_t { UINT16_MAX }; constexpr auto y = std::uint16_t { UINT16_MAX }; static_assert(multiply(x, y) == 1u, "broken math");
in a portable way that won't invoke undefined behavior. If that is enough for you to understand the problem at hand, you are welcome to skip the first two sections and jump straight to the section titled "Code for Review".
Otherwise, the section titled "Problem Statement" explains why simply writing x * y
would not have done the trick and the section "Proposed Solution" provides background information about the implementation of the multiply
function I'm asking review for.