When C has the / operator to divide two numbers, what is the purpose of having the div() library function?
Is there any scenario where / can't be used but div() can?
When C has the / operator to divide two numbers, what is the purpose of having the div() library function?
Is there any scenario where / can't be used but div() can?
Quoted from C Programming: A Modern Approach, 2nd Edition, chapter 26, Q & A section.
Q: Why do the div and ldiv functions exist? Can't we just use the / and % operators?
A:
divandldivaren't quite the same as/and%. Recall from Section 4.1 that applying/and%to negative operands doesn't give a portable result in C89. Ifiorjis negative, whether the value ofi / jis rounded up or down is implementation defined, as is the sign ofi % j. The answer computed bydivandldiv, on the other hand, don't depend on the implementation. The quotient is rounded toward zero; the remainder is computed according to the formulan = q x d + r, wherenis the original number,qis the quotient,dis the divisor, andris the remainder. Here are a few examples:n | d | q | r --------|--------|--------|-------- 7 | 3 | 2 | 1 -7 | 3 | -2 | -1 7 | -3 | -2 | 1 -7 | -3 | 2 | -1In C99, the
/and%operators are guaranteed to produce the same result asdivandldiv.Efficiency is the other reason that
divandldivexist. Many machines have an instruction that can compute both the quotient and remainder, so callingdivorldivmay be faster than using the/and%operators separately.
Too slow, yet redundant. At least glibc doc state that for case when gcc is used. I tried div to reimplement existing itoa() function (integer to ascii), expecting gcc to have builtin implementation for such a trivial thing, but gcc doesn't have it.
char *p = buf;
div_t d = {.quot = n};
while (1)
d = div (d.quot, 10) ,
*p++ = '0' + d.rem ;
Above code was 5..7 times slower than with separate operators:
char *p = buf;
while (1)
*p++ = '0' + n % 10,
n /= 10;