Skip to content

Instantly share code, notes, and snippets.

@jvranish
Last active May 2, 2022 19:17
Show Gist options
  • Save jvranish/3e2c3828645c139b8590ea30333cd72f to your computer and use it in GitHub Desktop.
Save jvranish/3e2c3828645c139b8590ea30333cd72f to your computer and use it in GitHub Desktop.
Simple option type in C
//usr/bin/make -s "${0%.*}" CFLAGS="-O2 -Wall -Werror" && ./"${0%.*}" "$@"; s=$?; rm ./"${0%.*}"; exit $s
#include <stdio.h>
#include <stdbool.h>
enum option_tag { OPTION_SOME, OPTION_NONE };
#define option_type(T) { enum option_tag tag; T some; }
#define SOME(S) { .tag = OPTION_SOME, .some = S }
#define NONE() { .tag = OPTION_NONE }
#define if_some(A, X) for (bool _once = true; _once; _once = false) /* execute only once */ \
for (typeof(A) _a = (A); _once; _once = false) /* only evaluate A once */\
if (_a.tag == OPTION_SOME) /* check tag */\
for (X = _a.some; _once; _once = false) /* we match! so assign local binding */
struct option_int option_type(int);
static struct option_int compute_a_thing(void) {
printf("computing things!\n");
struct option_int a_thing = SOME(5);
//a_thing = (struct option_int)NONE();
return a_thing;
}
int main(int argc, char const *argv[])
{
if_some(compute_a_thing(), int x) {
// x is locally scoped here and assigned the unwrapped result
printf("we have a thing: %d\n", x);
} else {
printf("nope\n");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment