generic 매크로 함수에 unsigned 사용하기

PGD·2022년 1월 9일
0

전처리기를 사용해 generic type 함수를 정의할 수 있다.
그러나 unsigned int 혹은 unsigned float 타입을 사용하는 경우, type##_max가 usigned int_max 처럼 돼 버리므로 함수 이름이 성립되지 않는다.

#include <stdio.h>

#define GENERIC_MAX(type) \
type type##_max(type x, type y) { return x > y ? x : y; }

GENERIC_MAX(unsigned long);

int main() {
    
    return 0;
}

위 코드 실행 결과는 다음과 같다.

...

extern void funlockfile (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__));
# 868 "/usr/include/stdio.h" 3 4

# 2 "main.c" 2





# 6 "main.c"
unsigned long unsigned long_max(unsigned long x, unsigned long y) { return x > y ? x : y; };

int main() {

    return 0;
}

다음 문구에 주목하면
unsigned long unsigned long_max(unsigned long x, unsigned long y) { return x > y ? x : y; };
함수 이름에 공백이 들어갔다는 걸 알 수 있다. syntax 에러를 유발한다.

그래서 다음과 같이 고쳐서 unsigned 타입들을 사용할 수 있다.

#include <stdio.h>

#define GENERIC_MAX(type) \
type type##_max(type x, type y) { return x > y ? x : y; }
#define UTYPE unsigned long

GENERIC_MAX(float);

GENERIC_MAX(UTYPE);

int main() {
    
    return 0;
}
  • 실행 결과
...

extern void funlockfile (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__));
# 868 "/usr/include/stdio.h" 3 4

# 2 "main.c" 2






# 7 "main.c"
float float_max(float x, float y) { return x > y ? x : y; };

unsigned long UTYPE_max(unsigned long x, unsigned long y) { return x > y ? x : y; };

int main() {

    return 0;
}

함수 이름이 적절하게 바뀌었다.

profile
student

0개의 댓글