Built-in arithmetic expressions only exits for homogeneous operand types. Any expression involving mixed types implies integral promotions, and the arithmetic operation itself is only ever defined for and applied to homogeneous types.
Choose either int32_t
or int64_t
.
As you probably understand correctly, for both choices of type arithmetic operations (at least +
, -
and *
) are susceptible to UB by overflow, but there can be no overflow when operating on two int64_t
s which both can be represented as int32_t
s. So for example the following works:
int64_t multiply(int32_t a, int32_t b)
{
// guaranteed not to overflow, and the result value is equal
// to the mathematical result of the operation
return static_cast(a) * static_cast(b);
}
As an example, here is how GCC translates this to x86 and x86_64 on Linux (note the different calling conventions):
multiply(int, int):
// x86 (32-bit, "-m32 -march=i386") x86-64 ("-m64 -march=x86-64")
// args are on the stack args are in EDI, ESI
// return in EDX:EAX return in RAX
mov eax, DWORD PTR [esp+8] movsx rax, edi
movsx rsi, esi
imul DWORD PTR [esp+4] imul rax, rsi
ret ret