기타/C++
[C++] constexpr
Wings of Freedom
2021. 3. 30. 13:01
constexpr 키워드는 컴파일러가 함수를 계산하게 하는 키워드입니다. 다음과 같이 함수 인자로 상수 표현식을 취하는 경우에 컴파일러가 constexpr 함수를 계산할 수 있습니다.
C++11에서는 constexpr기능을 확장하여 하나의 return 구문으로만 이루어질 수 있으며, C++14에서는 간단한 루프도 허용이 됩니다.
다음은 constexpr 표현식과 문법 규칙을 설명한 내용입니다.
// constexpr example
constexpr double scale = 10;
constexpr Point scale(Point p) { return xscale * xscale; }
int glob = 9;
constexpr void bad(int &arg){ // error : no return statement
++args; // error : change the state of the caller's side argument
glob = 7; // error : revise a non-local variable
}