Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

div — C23 utility function

`div(numer, denom)` from `<stdlib.h>` computes integer quotient and remainder in one operation, returning `div_t` with `quot` and `rem`. Integer division truncates toward zero, and `numer == quot * denom + rem`.

Version: C23

Syntax

div_t div(int numer, int denom);

div(numer, denom) from <stdlib.h> computes integer quotient and remainder in one operation, returning div_t with quot and rem. Integer division truncates toward zero, and numer == quot * denom + rem.

The example calls div(-17, 5). Output -3 -2 -17 shows the quotient truncated toward zero, a remainder with the numerator’s sign, and reconstruction of the original value.

denom must be nonzero. If either quotient or remainder is not representable as int—including INT_MIN / -1—behavior is undefined. Use ldiv and lldiv for long and long long instead of narrowing their arguments.

Examples

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    div_t result = div(-17, 5);
    printf("%d %d %d\n", result.quot, result.rem, result.quot * 5 + result.rem);
    return 0;
}

Result

-3 -2 -17

The example calls `div(-17, 5)`. Output `-3 -2 -17` shows the quotient truncated toward zero, a remainder with the numerator’s sign, and reconstruction of the original value.

Sources