What is the purpose of the div() library function?

Viewed 5126

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?

6 Answers

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: div and ldiv aren'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. If i or j is negative, whether the value of i / j is rounded up or down is implementation defined, as is the sign of i % j. The answer computed by div and ldiv, on the other hand, don't depend on the implementation. The quotient is rounded toward zero; the remainder is computed according to the formula n = q x d + r, where n is the original number, q is the quotient, d is the divisor, and r is 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     | -1

In C99, the / and % operators are guaranteed to produce the same result as div and ldiv.

Efficiency is the other reason that div and ldiv exist. Many machines have an instruction that can compute both the quotient and remainder, so calling div or ldiv may 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;
Related