#define보다는 const, enum, inline

모르핀·2021년 4월 12일
0

C++기초

목록 보기
2/7

#define보다는 const, enum, inline

#define ASPECT_RATIO 1.653 // preprocessor에서 상수로 만들어 버림
const ASPECT_RATIO = 1.653; //

매크로를 사용하면 에러가 발생했을 때 곤란할 수 있다.
기호 테이블(Symbol table)에 들어가지 않기 때문에 에러에서는 ASPECT_RATIO가 아닌 1.653로 표기된다.

#define을 상수, enum으로 교체

상수 포인터(constant pointer)

포인터와 포인터가 가르키는 자료 모두 const로 만들어 주어야 한다.
ex) const char const authorName = "Scott Meyers";

클래스 멤버

class GamePlayer
{
private:
    static const int NumTurns = 5; // 선언(declaration)된것 정의된 것이 아님
    int scores[NumTurns];
...

만약 const로 선언한 변수의 주소를 알려주기 싫다면 enum을 사용하는 것을 고려해보자

class GamePlayer
{
private:
    enum { NumTurns = 5 }; 
    int scores[NumTurns];
...

#define을 inline으로 교체

#include <iostream>
#define MAX(a,b) (((a)>(b))?(a):(b))

int main(void)
{
    int x = 6;
    int y = 0;

    MAX(++x, y);
    cout << x << ", " << y << endl; // 8, 0
    MAX(x, y + 10);
    cout << x << ", " << y << endl; // 9, 0
}

함수 호출을 없애기 위해서 매크로 함수를 쓰면 이런 이상한 결과가 나올 수 있다.

template <typename T>
inline T MAX (T a, T b)
{
    if (a > b)
        return a;
    else
        return b;
}

그럴 경우 인라인 함수를 사용하면 이러한 문제점을 미리 예방할 수 있다.

profile
플어머

0개의 댓글