typestar

Error codes and out-parameters in C

The C convention: return success or failure, deliver the value through a pointer.

#include <stdlib.h>
#include <string.h>

int parse_pair(const char *text, int *first, int *second) {
    if (text == NULL || first == NULL || second == NULL) {
        return 0;
    }
    const char *comma = strchr(text, ',');
    if (comma == NULL) {
        return 0;
    }
    *first = atoi(text);
    *second = atoi(comma + 1);
    return 1;
}

int use_it(void) {
    int a = 0;
    int b = 0;
    if (!parse_pair("3,4", &a, &b)) {
        return -1;
    }
    return a * b;
}

How it works

  1. Zero or negative for failure keeps the check uniform.
  2. The out-parameter is only written on success.
  3. Callers can then chain checks without nesting deeply.

Keywords and builtins used here

The run, in numbers

Lines
24
Characters to type
404
Tokens
138
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 83 seconds.

Type this snippet

Step 1 of 4 in Signatures, step 1 of 11 in APIs, errors & testing.

Next →