When C has the / operator to divide two numbers, what is the purpose of having the div() library function?
Is there any scenario where /
As other people have mentioned, div() will give you both the
quotient and the remainder. This is because the (software) integer
division algorithm that most C runtimes use computes both at the same
time.
If the target computer does not have a hardware divider, the /
operator typically gets turned into a call to div() and the
remainder gets thrown away. The same thing happens with the %
operator except that it's the quotient that gets tossed. So if you're
doing something like this:
quot = a / b;
rem = a % b;
you're calling the divide routine twice (and divide is pretty slow if
your computer doesn't do it in hardware). So it's faster to use
div() to get both.
(Of course, it's also less readable and whether you actually gain any
performance advantage depends on your specific platform and compiler.
You should only ever switch to div() if you've determined that it's
a performance bottleneck. Remember what Knuth said about premature
optimization.)