Skip to content

Instantly share code, notes, and snippets.

@hborders
Created March 13, 2017 15:14
Show Gist options
  • Save hborders/1ceff6f208e73b8986b971b9b282a259 to your computer and use it in GitHub Desktop.
Save hborders/1ceff6f208e73b8986b971b9b282a259 to your computer and use it in GitHub Desktop.
A C union with an enum tag to differentiate types
#include <stdio.h>
typedef enum {
FooType,
BarType,
} Type;
typedef struct {
char *f;
char *g;
} Foo;
typedef struct {
int b;
int c;
} Bar;
typedef struct {
Type type;
union {
Foo foo;
Bar bar;
};
} Example;
void printExample(Example example) {
switch (example.type) {
case FooType: {
Foo foo = example.foo;
printf("Foo: %s, %s\n", foo.f, foo.g);
break;
}
case BarType: {
Bar bar = example.bar;
printf("Bar: %d, %d\n", bar.b, bar.c);
break;
}
}
}
int main(void) {
Example fooExample = {
.type = FooType,
.foo = {
.f = "foo",
.g = "goo",
},
};
Example barExample = {
.type = BarType,
.bar = {
.b = 2,
.c = 3,
},
};
printExample(fooExample); // Foo: foo, goo
printExample(barExample); // Bar: 2, 3
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment