[C++] 절대 변하지 않을 변수를 상수화를 시켜보자

2022. 6. 27. 21:33코딩 1막 <C++개념편>/코딩 1막 <C++응용편>

728x90
#define PI 3.1415f
#define COL 100
#define ROW 64.9f

const float pi = 3.1415f;

void Func(const int& inputA, const int& inputB)	// 참조자 & : 별명이라고 생각하셈. 참조자는 공간을 쓰지 않는다.
{
	cout << inputA << endl;
	cout << inputB << endl;
}

void main()
{
	// **constexpr 컴파일시점에만 상수화, 초기화를 시켜준다
	// **런타임(실행 후)때는 constexpr을 적용할 수 없다.
	// int input;
	// cin >> input;
	// constexpr int count = input;	오류발생(런타임적용X)
	
	cout << "const로 상수화한 변수 : " << 5 * pi << endl; 
	cout << "define 전처리기를 사용한 상수화 : " << 5 * PI << endl;

	// const 상수는 반드시 선언과 동시에 초기화를 해야한다.
	// 일반적으로 상수는 대문자로 쓴다.
	const int WIDTH = 50;
	const int HEIGHT = 120;

	cout << "define COL = " << COL << endl;
	cout << "define ROW = " << ROW << endl;
	cout << "const int WIDTH = " << WIDTH << endl;
	cout << "const int HEIGHT = " << HEIGHT << endl;
}

출력 결과

728x90