Created
March 13, 2017 15:14
-
-
Save hborders/1ceff6f208e73b8986b971b9b282a259 to your computer and use it in GitHub Desktop.
A C union with an enum tag to differentiate types
This file contains hidden or 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 <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