I have the following C/C++ code (compiler explorer link):
void update_mul(int *x, int *amount) {
*x *= *amount;
}
void update_add(int *x, int *amount) {
*x += *amount;
}
Under both clang and gcc compiling as C or as C++ with at least -O1
enabled, the above translates to this assembly:
update_mul: # @update_mul
mov eax, dword ptr [rdi]
imul eax, dword ptr [rsi]
mov dword ptr [rdi], eax
ret
update_add: # @update_add
mov eax, dword ptr [rsi]
add dword ptr [rdi], eax
ret
It seems like for add it's doing something like:
register = *amount;
*x += register;
But for multiply it's doing:
register = *x;
register *= *amount;
*x = register;
Why does the multiplication require an extra instruction over the add, or is it not required but just faster?
mov
: godbolt.org/z/YTfTKe75o – Andry