'#'에 해당되는 글 1건

  1. 2008/06/03 [C언어]매크로의 샵(#)숄레이션~ (1)
[左腦]좌뇌/컴퓨터2008/06/03 09:19

매크로에서 샵(#)을 활용하는 법을 알아보자.

int main()
{
 int a = 100, b = 20, c;
 float fa = 50.2, fb = 20.4, fc = 0.0;

 c=fun(add, int, a, b); out(add, int, c);
 c=fun(div, int, a, b); out(div, int, c);
 c=fun(mul, int, a, b); out(mul, int, c);

 fc=fun(add, float, a, b); out(add, float, fc);
 fc=fun(div, float, a, b); out(div, float, fc);
 fc=fun(mul, float, a, b); out(mul, float, fc);
 return 1;
}

여기서 fun과 out을 구현하는 방법은?
파라미터로 int 와 float 라는 형이 넘어가는데 C언어에서 이 형을 구분하는 함수를 만들려면 매크로 함수를 이용해야 한다.
매크로 함수의 샵(#)을 이용하면 간단하게 구현된다.
##은 두 문자열을 이어준다.(매크로 함수내에서)
#은 매크로항을 문자열로 가져온다.

#define fun(name0, name1, x, y) name0##_##name1(x,y)
이거 하나로 간단하게 fun 함수 구현 끝
#define out(name0, name1, data) out_##name1(name0, name1, data)

#define out_int(name0, name1, data) printf(#name0"_"#name1" : [%d]\n", data)
#define out_float(name0, name1, data) printf("#name0"_"#name1" : [%f]\n", data)

추가) out_ 시리즈의 printf 문 내부는 " " 들의 연속으로 구성된다.

char str[] = "우에" "아잉"
printf("%s\n" "우에", str);

이렇게 하면...
결과는
우에 아잉 우에
" " 들끼리는 서로 합체된다-.-

Creative Commons License
Posted by 우에
TAG , ,

댓글을 달아 주세요

  1. 전처리기 #이 뭔지 까먹었었는데, 잘 보고 갑니다. ^^

    2010/07/07 15:38 [ ADDR : EDIT/ DEL : REPLY ]