Last active
December 12, 2021 20:05
-
-
Save RealNeGate/94a3074dd4e6d29ee3170f4a70c3dad2 to your computer and use it in GitHub Desktop.
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
// the macros could be made to not do | |
// anything on codebases that wanna support both | |
#ifdef __CUIK_C__ | |
#include <cuik.h> | |
#else | |
#define cuik_tag | |
#define cuik_tagged(val) | |
#define cuik_try_use(a, b) ((a) == (b)) | |
#define cuik_tag_switch switch | |
#endif | |
typedef enum ValueType { | |
VAL_NUM, | |
VAL_STRING | |
} ValueType; | |
typedef struct Value { | |
cuik_tag ValueType tag; | |
union { | |
cuik_tagged(VAL_NUM) int num; | |
cuik_tagged(VAL_STRING) char* str; | |
}; | |
} Value; | |
int add(Value v, int i) { | |
// let's say it only works on numbers | |
if (cuik_try_use(v.tag, VAL_NUM)) { | |
// simply put, you can't access '.str' within here | |
return v.num + i; | |
} | |
abort(); | |
} | |
void print_val(const Value* v) { | |
cuik_tag_switch (v->tag) { | |
case VAL_NUM: | |
printf("Number: %d\n", v->num); | |
break; | |
case VAL_STR: | |
printf("String: '%s'\n", v->str); | |
break; | |
default: | |
// considered an assertion in debug for me | |
__builtin_unreachable(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment