Skip to content

Instantly share code, notes, and snippets.

@ChristopherRabotin
Created February 5, 2019 06:32
Show Gist options
  • Save ChristopherRabotin/bc92a6a10e5e5e00e9db4563711a67a1 to your computer and use it in GitHub Desktop.
Save ChristopherRabotin/bc92a6a10e5e5e00e9db4563711a67a1 to your computer and use it in GitHub Desktop.
A result like type in C using a struct and a union
/*
Output:
$ gcc rslt.c -o rslt && ./rslt
[OK] kind=0 data=15.159000 errno=8389
[!!] kind=1 data=0.000000 errno=-3
size = 16
*/
#include <stdio.h>
enum _rslt_kind_ { Ok = 0, Err = 1 };
typedef struct {
enum _rslt_kind_ kind;
union {
double value;
short errno;
} data;
} rslt_dbl;
void rst_rslt_dbl(rslt_dbl *rslt) {
rslt->kind = Ok;
rslt->data.errno = 0;
rslt->data.value = 0.0;
}
void ok_test(rslt_dbl *rslt) {
rslt->kind = Ok;
rslt->data.value = 15.159;
}
void err_test(rslt_dbl *rslt) {
rslt->kind = Err;
rslt->data.errno = -3;
}
void print_rslt_dbl(const rslt_dbl *my_rslt) {
switch (my_rslt->kind) {
case Ok:
printf("[OK] kind=%d\tdata=%f\terrno=%d\n", my_rslt->kind,
my_rslt->data.value, my_rslt->data.errno);
break;
default:
printf("[!!] kind=%d\tdata=%f\terrno=%d\n", my_rslt->kind,
my_rslt->data.value, my_rslt->data.errno);
}
}
void main() {
rslt_dbl my_rslt;
ok_test(&my_rslt);
print_rslt_dbl(&my_rslt);
// Reset the struct otherwise the previous data is still there
rst_rslt_dbl(&my_rslt);
err_test(&my_rslt);
print_rslt_dbl(&my_rslt);
printf("size = %d\n", sizeof(my_rslt));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment