const 키워드와 함께 정의한 변수의 값는 수정이 불가능하다. 즉 상수화 되어버리는데, 프로그래밍시에 바뀌어서는 안될값이 있을 경우 활용할 수 있다. 코드가 길어질 경우 실수로 변수의 값이 바뀌어 지는것을 방지할 수 있다.
Ex1> 배열의 크기를 상수화하여 전역에서 사용한다.
#include "stdafx.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
const unsigned short arraySize = 100;
int number[arraySize] = { 0 };
for (int i = 0; i < arraySize; i++)
{
cout << i + 1 << "::" << number[i] << "\n";
}
return 0;
}
Ex2> 포인터 또한 다음과 같은 유형으로 상수화 할 수 있다.
#include "stdafx.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int number1 = 10;
int number2 = 20;
// Ex 1>
// 포인터가 가리키는 값이 const일 경우
const int* pointer_ex1 = &number1;
// 포인터값은 변경가능하다
pointer_ex1 = &number2;
// [Error] 가리키는 값을 변경할 수 없다.
//*pointer_ex1 = 30;
cout << *pointer_ex1 << "\n";
// Ex 2>
// 포인터가 const 일경우
int* const pointer_ex2 = &number1;
// [Error] : 포인터값을 변경할 수 없다
// pointer_ex2 = &number2;
// 가리키는 값은 변경가능하다
*pointer_ex2 = 30;
cout << *pointer_ex2 << "\n";
// Ex 3>
// 포인터와 가리키는 값이 const 일경우
const int* const pointer_ex3 = &number1;
// [Error] : 포인터값을 변경할 수 없다
// pointer_ex2 = &number2;
// [Error] 가리키는 값을 변경할 수 없다.
//*pointer_ex2 = 30;
cout << *pointer_ex3 << "\n";
return 0;
}