Language/C++

const / #define / constexpr 차이점

피퍄퓨퍄 2019. 3. 1. 01:44

const 


read only data memory에 할당됨 = 주소를 직접 건들이면 const값 변경가능

type을 명시적으로 기록해서 조금 더 안전하다.

#define와 같은용도로 사용된 const의경우 release로 build하면 compiler가 자동으로 삭제해준다.

const는 값에 대해서만 한정지을 수 있어 충분히 compile time에도 할 수 있는 연산도 run time에 해야한다.



#define


메모리에 올라가지 않음 = 임베디드처럼 memory가 부족한 곳에서는 사용해야한다.

type을 기록하지 않음

초기 C언어에서 const가 없을때 사용했었음



constexpr 


변수 함수, 클래스를 compile time에 정수로 사용할 수 있다.

즉 상수로 취급할 수 있는 작업은 compile time에 처리하도록 한다.



const / constexpr 차이점


constexpr의 할당시기는 compile time때 확정되어야 한다.

const의 할당시기는 compile time, run time 아무때나 상관없으나 code에는 어떤 값이 할당되도록 code가 쓰여야 한다.



    
constexpr int max = 100;
void use(int n)
{
constexpr int c1 = max + 7; // OK
constexpr int c2 = n + 7 // error
const int c3 = n + 7 // OK

int p1 = 10;
constexpr int c4 = p1 + 1; // error

const int c5; // error
c3 = 4 // error
}



참고

https://haedallog.tistory.com/81?category=795069