I hear that when the processor does / or %, it will perform the same operation but one way it returns the quotient, the other way the remainder.
Is it possible to get both in a single operation? Maybe if I throw in a snippet of assembly code (which I've never done)?
Yes, the compiler will do it for you. Just use a divide followed by a remainder with the same operands.
https://godbolt.org/z/oK4f4s
void div(int n, int d, int *q, int *r)
{
*q = n / d;
*r = n % d;
}
div(int, int, int*, int*):
mov eax, edi
mov r8, rdx
cdq
idiv esi
mov DWORD PTR [r8], eax
mov DWORD PTR [rcx], edx
ret
Is it possible to get both in a single operation?
No, there is no such operator in C++. There is function in the standard library which does both operations: std::div
But this doesn't matter. Whether you have one or two operations in C++ doesn't mean that the cpu would have to perform that many operations. A half decent optimiser will be able to translate both operations into a single instruction (assuming that is possible with the target CPU).
Yes. That's what the functions std::remquo
and std::div
do.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.