Programming/C

if-else 구조 vs lookup table구조

moxie2ks 2025. 3. 13. 18:01
728x90
반응형

개요

C 언어를 사용하다 보면 if-else 구문을 많이 사용할 것이다. 하지만 if-else 구조가 많아질수록 효율성은 많이 떨어지게 된다.
이때, if-else 구조로 처리해야 하는 로직이 많을 경우 lookup table 형식으로 보다 효율적인 코딩 및 유지보수를 할 수 있다.

if-else 구조 예제 코드

아래는 기본적인 if-else를 사용하여 특정 조건에 맞는 값을 리턴하는 코드이다.

#include <stdio.h>
#include <string.h>

#define PG_CIPHER_AES_GCM            0
#define PG_CIPHER_AES_CTR            1
#define PG_CIPHER_AES_KWP            2
#define PG_CIPHER_AES_XTS            3
#define PG_CIPHER_ARIA_CBC            4
#define PG_CIPHER_ARIA_CTR            5
#define PG_CIPHER_ARIA_GCM            6
#define PG_CIPHER_SEED_CBC            7
#define PG_MAX_CIPHER_ID            7
#define PG_CIPHER_DEFAULT            PG_CIPHER_AES_XTS

int
pg_get_cipher(char *ciphername)
{
if (ciphername == NULL)
     return PG_CIPHER_DEFAULT;

if (strncasecmp(ciphername, "AES", 3) == 0)
     return PG_CIPHER_AES_KWP;
else if (strncasecmp(ciphername, "ARIA", 4) == 0)
     return PG_CIPHER_ARIA_CBC;
else if (strncasecmp(ciphername, "SEED", 4) == 0)
     return PG_CIPHER_SEED_CBC;

return PG_CIPHER_DEFAULT;
}

int main(void) {

    printf("%d\n", pg_get_cipher("SEED128"));
    return 0;
}

코드 분석

위 코드는 사용상 아무 문제가 발생하지 않으나, else if구문이 많아진다면, 코딩 시간과 효율성이 매우 떨어진다. 이럴 경우에는 이름, 이름에 해당하는 상수 값을 가지는 구조체를 배열 형태로 정의하고, 이를 순회하면서 로직을 수행하는 방법을 사용할 수 있다.

lookup table 구조 예제 코드

#include <stdio.h>
#include <string.h>

#define PG_CIPHER_AES_GCM            0
#define PG_CIPHER_AES_CTR            1
#define PG_CIPHER_AES_KWP            2
#define PG_CIPHER_AES_XTS            3
#define PG_CIPHER_ARIA_CBC            4
#define PG_CIPHER_ARIA_CTR            5
#define PG_CIPHER_ARIA_GCM            6
#define PG_CIPHER_SEED_CBC            7
#define PG_MAX_CIPHER_ID            7
#define PG_CIPHER_DEFAULT            PG_CIPHER_AES_XTS

typedef struct {
    char *name;
    int cipher;
} EncryptionNameEntry;

static EncryptionNameEntry encryption_name_table[] = {
    {"AES", PG_CIPHER_AES_KWP},
    {"ARIA", PG_CIPHER_ARIA_CBC},
    {"SEED", PG_CIPHER_SEED_CBC},
    {NULL, PG_CIPHER_DEFAULT}
};

int
pg_get_cipher(char *encryption_name)
{
    if (encryption_name == NULL)
        return PG_CIPHER_DEFAULT;

    for (EncryptionNameEntry *entry = encryption_name_table; entry->name != NULL; ++entry) {
        if (strncasecmp(encryption_name, entry->name, strlen(entry->name)) == 0) {
            return entry->cipher;
        }
    }

    return PG_CIPHER_DEFAULT;
}

int main(void) {

    printf("%d\n", pg_get_cipher("SEED128"));
    return 0;
}

코드 분석

이름, 이름에 해당하는 상수 값을 가지는 구조체를 배열 형태로 정의하고, 이를 순회하면서 로직을 수행하는 방법을 사용한 코드이다. 이렇게 하면 새로운 데이터 값을 여러 번 추가하는 경우 encryption_name_table에 데이터를 추가하기만 하면 관리가 수월해지고 코드 가독성이 증가하게 할 수 있다.

728x90
반응형