본문 바로가기
  • 쓸쓸한 개발자의 공부방

constexpr3

[C++] range-for, if init, if constexpr range-for - C++부터 지원하는 새로운 모양의 반복문 - 배열 뿐 아니라 STL의 다양한 컨테이너 list, vector, set 등 사용이 가능하다. - auto와 같이 사용되는 경우가 많다. #include int main() { int x[10] = {1,2,3,4,5,6,7,8,9,10}; for ( auto n : x ) { std::cout 2021. 8. 12.
[C++] 함수 : constexpr function constexpr function https://en.cppreference.com/w/cpp/keyword/constexpr constexpr 상수 constexpr int c = 1; constexpr function : 함수 앞에 constexpr 이 있는 형태 - 컴파일 할 때 값을 결정할 수 있으면, 컴파일 할 때 함수를 바로 실행한다. - 함수 인자값을 컴파일 시간에 결정할 수 없으면, 실행시간에 함수를 실행한다. constexpr int add(int a, int b) { return a + b; } int main() { int x = 1; int y = 1; int n1 = add(1, 1); // 컴파일 할 때 값을 결정할 수 있으면, 컴파일 할 때 함수를 바로 실행함. int n2 =.. 2021. 8. 10.
[C++] 변수 선언 : constexpr, structure binding constexpr 컴파일 시간에 상수 값이 결정된다. (c++11 부터 도입) const 와 constexpr은 변수 값이 한 번 set되면 값을 변경을 허용하지 않는다. constexpr은 컴파일 시간에만 상수를 만들 수 있다. c++에서는 constexpr를 쓰도록 추천한다. int main() { const int c1 = 10; c1 = 20; // error constexpr int c2 = 10; c2 = 20; // error } const는 10을 바로 set해주면서 값을 지정할 수 있고, 실행시간에 알 수 있도록 n 을 우변에 넣어 줄 수도 있다. 하지만 이는 정확하지 않고 문제가 발생할 소지가 있어 c++에서 constexpr을 새롭게 소개한다. void foo( const int s).. 2021. 8. 7.