4.15 Symbolic constants: const and constexpr variables

주홍영·2022년 3월 11일
0

Learncpp.com

목록 보기
53/199

Const variables

때로는 variable의 value가 고정되어있는 것이 유용할 때도 있다
예를 들어 중력이나 전자 전하량 등
사용하는 방법은 다음과 같다

const double gravity { 9.8 };  // preferred use of const before type
int const sidesInSquare { 4 }; // "east const" style, okay, but not preferred

Constant variables are sometimes called symbolic constants (as opposed to literal constants, which are just values that have no name).

앞서 살펴본 literal constant와 다르게 변수명이 존재하나 constant 이므로
symbolic constant라고도 부른다

Const variables must be initialized

const variable은 항상 initialize 되어야 한다, 선언과 동시에
그렇지 않으면 error가 발생한다

const variable은 일반 변수로 초기화할 수 있다
참조로 가져오는 것이 아닌 value로 가져오니 값이 변할 가능성은 없기에 가능한 것 같다

Runtime vs compile-time constants

Runtime constant는
실행이 되어봐야 하는 것이다
compile 때에는 const variable이 무엇을 의미할지 명확하게 결정할 수 없다
예를들어 함수 선언시 parameter를 const로 선언하는 경우에는
value를 전달 받아야지 variable이 그때 비로소 결정 되므로 runtime constant다

반면 다음과 같은 경우

const double gravity { 9.8 }; // the compiler knows at compile-time that gravity will have value 9.8
const int something { 1 + 2 }; // the compiler can resolve this at compiler time

컴파일러는 컴파일하면서 gravity와 something이 앞으로 어떻게 쓰일지 알 수 있다
이러한 complie-time constant는 컴파일러가 optimization하도록 도울 수 있다
마치 #define으로 치환하듯이 컴파일 과정에서 gravity나 something을 만나면
정해진 값으로 대체하면 되기때문이다.

constexpr

To help provide more specificity, C++11 introduced the keyword constexpr, which ensures that a constant must be a compile-time constant:
c++11에서 소개된 키워드로 compile time constant임을 명시하는 문법이다

const functio parameter

함수 안에서 전달받은 인수를 바꾸지 않겠다는 의미를 내포한다
따라서 그냥 사용하지 않고 pass by reference로 사용하거나 한다
(we usually don’t const parameters passed by value

Avoid using object-like preprocessor macros for symbolic constants

그러면 #define으로 symbolic constant 사용하면 되는 것 아니냐는 의문을 가질 수 있다
하지만 여기에는 세가지 문제점이 있어서 const variable을 사용한다

  • 디버깅에서의 문제
    preprocessor이므로 컴파일 이전에 모든 값을 치환시켜 놓는다
    따라서 디버깅 할때 변수의 이름이 아닌 치환된 값으로 표기가 되므로
    디버깅 할 때 어려움이 생길 수 있다

  • 의도하지 않은 naming conflict 발생 가능성
    혹시나 다른 코드의 변수명과 같은 텍스트를 치환할 수도 있다
    이러면 error가 발생하게 되므로 이를 피하기 위해서 가급적이면 지양한다

  • 매크로는 일반적인 scoping rule을 따르지 않는다
    따라서 의도하지 않은 파일에 영향을 주어서 충돌을 발생시킬 수도 있다

profile
청룡동거주민

0개의 댓글