본문 바로가기

오래된 흔적/Effective C++

Item 1: Prefer const and inline to #define

"preprocessor보다 compiler를 선호하라"

< 예시 1 : define 상수 >

#define ASPECT_RATIO 1.653

#define으로 정의된 것은 컴파일러가 소스코드를 컴파일 하기 전에 프리프로세서에 의해서 코드로부터 제거가 된다. 
그러므로 ASPECT_RATIO는 심볼 테이블에 들어가지 않는다.

< 발생될 수 있는 문제점 >

1. constant를 사용하는 소스 컴파일 시 confusing할 수 있다. 왜냐하면, ASPECT_RATIO가 아닌 1.653을 참조하기 때문.
2. 만약에 ASPECT_RATIO를 헤더 파일에 선언 하고, 그 헤더파일을 인클루드 하지 않으면 1.653이 어디서 왔는지 알수가 없다. 찾는데 개고생 할 소지가 있음. 

< 해결 제안 >

preprocessor macro 사용하지 말고 constant를 define해라. 

const double ASPECT_RATIO = 1.653;


< 예시 2 : define 함수 >

#define max(a, b)   ( (a) > (b) ? (a) : (b) )

함수 콜 오버헤드가 없으니 유용해서 많이 쓰는 것 중 하나. 

int a = 5, b = 0;
max(++a, b); // a is incremented twice
max(++a, b+10); // a is incremented once

< 해결 제안 >

inline 사용.

inline int max(int a, int b) { return a > b? a : b; }

type safe를 원하면 template을 사용.

template<class T> 
inline const T& max(const T& a, const T& b)
{ return a > b? a: b; }

또는 the standard C++ library의 max함수 써라..


'오래된 흔적 > Effective C++' 카테고리의 다른 글

References  (0) 2009.08.06