C++ const키워드와 포인터
EX
int x = 10;
int y = 20;
const int* p = &x; // pointer to const int
*p = 30; // error: can't change the value pointed to
p = &y; // ok: can change the pointer itself
1 포인터가 가리키는 값이 상수(constant pointed value): 이 경우, 포인터를 통해 값을 변경할 수 없습니다. 그러나 포인터 자체는 다른 곳을 가리킬 수 있습니다.
int x = 10;
int y = 20;
int* const p = &x; // const pointer to int
*p = 30; // ok: can change the value pointed to
p = &y; // error: can't change the pointer itself (i.e., it always points to 'x')
2 포인터 자체가 상수(constant pointer): 이 경우, 포인터가 한 번 설정되면 그것을 변경할 수 없습니다(즉, 다른 변수를 가리키도록 변경할 수 없음). 그러나 포인트가 가리키는 값을 변경하는 것은 가능합니다. cpp
int x=10;
const int* const p=&x;//constant pointer pointing to a constant integer
*p=20;//error : cannot change the value being pointed at.
y=20;
p=&y;//error : cannot change where the pointer is pointing.
3 상수를 가리키는 상수 포인터(constant pointer to a constant value) : 이 경우, 포인트 자체와 그것이 가리키는 값 모두 변경할 수 없습니다.
const의 위치는 매우 중요함
Leave a comment