linux-sysprog · intermediate · ~15 min
Follow the errno-setting convention in your APIs.
Follow the standard C convention: on error, set errno and return a sentinel; on success, return 0 and produce the result through an out-parameter.
Implement int checked_div(int a, int b, int *out). If b == 0, set errno = EDOM and return -1. Otherwise store a / b into *out and return 0.
a, b: integer dividend and divisor.out: where to store the quotient on success.0 on success (with *out set), or -1 on b == 0 (with errno == EDOM).
checked_div(10, 2, &o) -> 0 (o = 5)
checked_div(1, 0, &o) -> -1 (errno = EDOM)
b == 0: do not write *out; set errno and return -1.a, b: dividend and divisor; out: quotient output pointer.
0 on success (*out set); -1 with errno=EDOM when b==0.
On b==0 set errno=EDOM and return -1 without writing *out.
#include <errno.h>
int checked_div(int a, int b, int *out) {
/* TODO */
return -1;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.