Skip to content

Instantly share code, notes, and snippets.

@lucaswerkmeister
Created February 23, 2018 23:37
Show Gist options
  • Save lucaswerkmeister/685742f88f7b392b2cd777258423993c to your computer and use it in GitHub Desktop.
Save lucaswerkmeister/685742f88f7b392b2cd777258423993c to your computer and use it in GitHub Desktop.
little experiment on returning extra error information from functions in C
#include <errno.h>
#include <error.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
struct error {
int errnum;
const char *msg;
};
struct result_int {
bool ok;
int result;
struct error error;
};
struct result_int count_down(int c) {
if (c > 0) {
return (struct result_int) {
.ok = true,
.result = c - 1
};
} else {
return (struct result_int) {
.ok = false,
.error = (struct error) {
.errnum = EINVAL,
.msg = "counter must be strictly positive"
}
};
}
}
int main(int argc, char *argv[]) {
for (int argn = 1; argn < argc; argn++) {
struct result_int result = count_down(atoi(argv[argn]));
if (result.ok) {
printf("%d\n", result.result);
} else {
error(EXIT_FAILURE, result.error.errnum, "%s", result.error.msg);
}
}
return 0;
}
.PHONY: all
CFLAGS := -std=c99 -Wall -Wextra -Wpedantic
all: countdown
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment