Passion/Programming

C/C++ 매개변수를 갖는 매크로 #,## 연산자

sunshout 2013. 4. 15. 14:24

o  C/C++ 매개변수를 갖는 매크로 #,## 연산자

참조: http://iamaman.tistory.com/699

 

¡ #연산자

매개변수를 문자화 하는 연산자

#define STRING(x) #x

 

예제 (test.c)

#include <stdio.h>

 

#define STRING(x) #x

 

int main(int argc, char **argv)

{

    char *a = STRING(I am boy);

    printf("%s", a);

    return 0;

}

결과

[root@openxen test]# make test

cc     test.c   -o test

[root@openxen test]# ./test

I am boy[root@openxen test]#

 

¡ ##연산자

두 개의 토큰을 결합하는 역할 (변수를 선언할 때 주로 사용)

#define X(n) x##n

 

예제 (test2.c)

#include <stdio.h>

 

#define intX(n) int x##n = n

 

int main(int argc, char** argv)

{

    intX(1);

    intX(2);

    intX(3);

 

    printf("%d %d %d\n", x1, x2, x3);

}

 

결과

[root@openxen test]# make test2

cc     test2.c   -o test2

[root@openxen test]# ./test2

1 2 3