Embedded Artistry libc
C Standard Library Support for Bare-metal Systems
div.c File Reference
#include <stdlib.h>
Include dependency graph for div.c:

Go to the source code of this file.

Functions

div_t div (int num, int denom)
 Computes both the quotient and the remainder of the division of the numerator x by the denominator y. More...
 

Function Documentation

◆ div()

div_t div ( int  x,
int  y 
)

Computes both the quotient and the remainder of the division of the numerator x by the denominator y.

Computes both the quotient and the remainder of the division of the numerator x by the denominator y.

Parameters
xinteger values
yinteger values
Returns
If both the remainder and the quotient can be represented as objects of the corresponding type (int, long, long long, imaxdiv_t, respectively), returns both as an object of type
See also
div_t,
ldiv_t,
lldiv_t,
imaxdiv_t.

If either the remainder or the quotient cannot be represented, the behavior is undefined.

Definition at line 35 of file div.c.

36 {
37  div_t r;
38 
39  r.quot = num / denom;
40  r.rem = num % denom;
41  /*
42  * The ANSI standard says that |r.quot| <= |n/d|, where
43  * n/d is to be computed in infinite precision. In other
44  * words, we should always truncate the quotient towards
45  * 0, never -infinity.
46  *
47  * Machine division and remainer may work either way when
48  * one or both of n or d is negative. If only one is
49  * negative and r.quot has been truncated towards -inf,
50  * r.rem will have the same sign as denom and the opposite
51  * sign of num; if both are negative and r.quot has been
52  * truncated towards -inf, r.rem will be positive (will
53  * have the opposite sign of num). These are considered
54  * `wrong'.
55  *
56  * If both are num and denom are positive, r will always
57  * be positive.
58  *
59  * This all boils down to:
60  * if num >= 0, but r.rem < 0, we got the wrong answer.
61  * In that case, to get the right answer, add 1 to r.quot and
62  * subtract denom from r.rem.
63  */
64  if(num >= 0 && r.rem < 0)
65  {
66  r.quot++;
67  r.rem -= denom;
68  }
69  return (r);
70 }
int quot
Definition: stdlib.h:17
int rem
Definition: stdlib.h:18
Division type for integers.
Definition: stdlib.h:15

References div_t::quot, and div_t::rem.