C언어에서의 Tagged Union 구현

mhComa·2023년 4월 8일
0
#include <stdio.h>

typedef enum tu_foo_type_enum tu_foo_type;
typedef struct tu_foo_struct tu_foo;

enum tu_foo_type_enum {
	TU_FOO_INT,
	TU_FOO_STR
};

struct tu_foo_struct {
	tu_foo_type type;
	union {
		int i;
		char* str;
	};
};

void print_tu_foo(tu_foo tf) {
	switch (tf.type) {
		case TU_FOO_INT:
			printf("%d\n", tf.i);
		break;
		case TU_FOO_STR:
			puts(tf.str);
		break;
	}
}

int main(void) {

	tu_foo a;
	tu_foo b;

	a.type = TU_FOO_INT;
	a.i = 100;

	b.type = TU_FOO_STR;
	b.str = "asdf";

	print_tu_foo(a);	// 100 출력
	print_tu_foo(b);	// asdf 출력

	return 0;
}

type과 union을 struct로 묶으면 되는데,
type에 많은 정보가 필요없을 경우 uint8_t 같은 작은 자료형을 사용해도 될 것이다.

profile
Ich bin ein Hund!

0개의 댓글