Created
February 23, 2018 23:37
-
-
Save lucaswerkmeister/685742f88f7b392b2cd777258423993c to your computer and use it in GitHub Desktop.
little experiment on returning extra error information from functions in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.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