Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
05-09 01:20
관리 메뉴

nomad-programmer

[Programming/C] 구조체와 열거형 그리고 함수 포인터 본문

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])

함수 포인터의 배열을 사용하면 코드 관리가 훨씬 쉬워진다.

배열로 코드를 더 짧고 확장하기 쉽게 만들면 코드의 규모를 확장하기 좋다.

Comments