linux-sysprog · intermediate · ~15 min

Set errno in your own function

Follow the errno-setting convention in your APIs.

Challenge

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.

Task

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.

Input

  • a, b: integer dividend and divisor.
  • out: where to store the quotient on success.

Output

0 on success (with *out set), or -1 on b == 0 (with errno == EDOM).

Example

checked_div(10, 2, &o)   ->   0   (o = 5)
checked_div(1, 0, &o)    ->   -1  (errno = EDOM)

Edge cases

  • b == 0: do not write *out; set errno and return -1.

Input format

a, b: dividend and divisor; out: quotient output pointer.

Output format

0 on success (*out set); -1 with errno=EDOM when b==0.

Constraints

On b==0 set errno=EDOM and return -1 without writing *out.

Starter code

#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.