글
C++ 매크로를 호출할때 인수로 함수를 사용할 경우 매크로 본문에 주의하자.
Game Programming/C++
2010. 8. 26. 16:06
// inline_functions_macro.c #include <stdio.h> #include <conio.h> #define toupper(a) ((a) >= 'a' && ((a) <= 'z') ? ((a)-('a'-'A')):(a)) int main() { char ch; printf_s("Enter a character: "); ch = toupper( getc(stdin) ); printf_s( "%c", ch ); }
위 코드를 수행할 때
매크로를 호출할때 인수로 함수를 넘기면,
a >= 'a' 를 확인하기위해 getc 한번 호출되고
a <= 'z' 를 확인하기 위해 한번더 호출되고,
((a)-('a'-'A')):(a)) 를 하기 위해 한번더 호출되어
아래와 같은 결과를 출력한다.
Sample Input: xyz Sample Output: Z이때는 inline 을 사용하여 해결하자 !!!
// inline_functions_inline.cpp #include <stdio.h> #include <conio.h> inline char toupper( char a ) { return ((a >= 'a' && a <= 'z') ? a-('a'-'A') : a ); } int main() { printf_s("Enter a character: "); char ch = toupper( getc(stdin) ); printf_s( "%c", ch ); }
Sample Input: a Sample Output: A출처 : MSDN
http://msdn.microsoft.com/en-us/library/bf6bf4cf.aspx