, , , , , ++ 11. , , ( Godbolt).
constexpr int c = 2;
int signed_div(int in){
return in/c;
}
int unsigned_div(unsigned in){
return in/c;
}
:
signed_div(int):
mov eax, edi
shr eax, 31
add eax, edi
sar eax
ret
unsigned_div(unsigned int):
mov eax, edi
shr eax
ret
? shr eax, 31 ( 31) , , , eax == 0, eax == 1. eax. , " , 1 . ( ).
, 1, . .
, 1 . , , , , , . , , .
, , , .
--2 . , ( Godbolt).
constexpr int c = 3;
int signed_div(int in){
return in/c;
}
int unsigned_div(unsigned in){
return in/c;
}
:
signed_div(int):
mov eax, edi
mov edx, 1431655766
sar edi, 31
imul edx
mov eax, edx
sub eax, edi
ret
unsigned_div(unsigned int):
mov eax, edi
mov edx, -1431655765
mul edx
mov eax, edx
shr eax
ret
, . , mul imul ( , , , - , , ), , .