CKTIS / C
ldiv — C23 arithmetic utility function
`ldiv(numer, denom)` from `<stdlib.h>` computes a `long int` quotient and remainder in one operation and returns an `ldiv_t` with `quot` and `rem` members. Division truncates toward zero, and `numer == quot * denom + rem`.
Version: C23
Syntax
ldiv_t ldiv(long int numer, long int denom);ldiv(numer, denom) from <stdlib.h> computes a long int quotient and remainder in one operation and returns an ldiv_t with quot and rem members. Division truncates toward zero, and numer == quot * denom + rem.
The example calls ldiv(-17L, 5L) and prints -3 -2 -17. It demonstrates a quotient truncated toward zero, a remainder with the numerator’s sign, and exact reconstruction of the input.
denom must be nonzero. If the quotient or remainder is not representable as long—notably for LONG_MIN / -1L—behavior is undefined. Do not perform the reconstruction multiplication on untrusted values without overflow checks; use div for int and lldiv for long long.
Examples
#include <stdio.h>
#include <stdlib.h>
int main(void) {
ldiv_t result = ldiv(-17L, 5L);
printf("%ld %ld %ld\n", result.quot, result.rem, result.quot * 5L + result.rem);
return 0;
}
Result
-3 -2 -17
The example calls `ldiv(-17L, 5L)` and prints `-3 -2 -17`. It demonstrates a quotient truncated toward zero, a remainder with the numerator’s sign, and exact reconstruction of the input.