Programming/C
[Programming/C] 구조체와 열거형 그리고 함수 포인터
scii
2020. 6. 18. 01:09
열거형을 구조체의 멤버로 등록하고 사용하는 예제이다.
#include <stdio.h>
// 열거형 정의
enum play_type {
RUN, STOP, ATTACK
};
// response 구조체안에 열거형을 멤버로 넣었다.
typedef struct {
char *name;
enum play_type type;
} response;
void run(response r) {
printf("%s\n", r.name);
puts("run!");
}
void stop(response r) {
printf("%s\n", r.name);
puts("stop!");
}
void attack(response r) {
printf("%s\n", r.name);
puts("attack!");
}
int main(void) {
response r[] = {
{"haha", RUN},
{"hoho", STOP},
{"hehe", STOP},
{"huhu", ATTACK}
};
for (int i = 0; i < 4; i++) {
switch (r[i].type) {
case RUN:
run(r[i]);
break;
case STOP:
stop(r[i]);
break;
default:
attack(r[i]);
break;
}
}
return 0;
}
// 결과
/*
haha
run!
hoho
stop!
hehe
stop!
huhu
attack!
*/
함수 포인터를 추가하여 예제 소스 코드를 변경
#include <stdio.h>
enum play_type {
RUN, STOP, ATTACK
};
typedef struct {
char *name;
enum play_type type;
} response;
void run(response r) {
printf("%s\n", r.name);
puts("run!");
}
void stop(response r) {
printf("%s\n", r.name);
puts("stop!");
}
void attack(response r) {
printf("%s\n", r.name);
puts("attack!");
}
int main(void) {
response r[] = {
{"haha", RUN},
{"hoho", STOP},
{"hehe", STOP},
{"huhu", ATTACK}
};
// 함수 포인터 추가로 인해 switch문이 제거되었다. 더 깔끔한 모습
// void (*replies[])(response) = {run, stop, attack}; 명령과 동일하다.
void (*replies[])(response) = {&run, &stop, &attack};
for (int i = 0; i < 4; i++) {
// replies[r[i].type](r[i]); 명령과 동일하다.
(*(replies + r[i].type))(r[i]);
}
return 0;
}
// 결과
/*
haha
run!
hoho
stop!
hehe
stop!
huhu
attack!
*/
switch 문으로 일일이 함수를 호출하던 것을 다음의 한 문장으로 바뀌었다.
replies[r[i].type](r[i])
함수 포인터의 배열을 사용하면 코드 관리가 훨씬 쉬워진다.
배열로 코드를 더 짧고 확장하기 쉽게 만들면 코드의 규모를 확장하기 좋다.