Const 위치

#include <stdio.h>

int main(){
   int a = 30;
   int b = 20;

   const int *p = &a;
   //*p = 40;
   /*
const.c: In function 'main':
const.c:8:8: error: assignment of read-only location '*p'
    *p = 40;
       ^
   */
   p = &b;
   
   int const *p2 = &a;
   //*p2 = 40;
   /*
const.c: In function 'main':
const.c:12:9: error: assignment of read-only location '*p2'
    *p2 = 40;
        ^
   */
   p2 = &b;

   int* const p3 = &a;
   //p3 = &b;
   /*
const.c: In function 'main':
const.c:16:8: error: assignment of read-only variable 'p3'
    p3 = &b;
       ^    
   */
   *p3 = 100;

   return 0;
}

첫번째

    const int *p = &a;
   //*p2 = 40;
   p2 = &b

const는 현재 int*에 걸려있는 것이다. 그래서 *p는 수정이 안되지만, p는 수정이 가능하다.

두번째

    int const *p2 = &a;
   //*p2 = 40;
   /*
const.c: In function 'main':
const.c:12:9: error: assignment of read-only location '*p2'
    *p2 = 40;
        ^
   */
   p2 = &b;

이 케이스 또한 첫번째와 마찬가지이다. const가 걸리는 대상은 *p2다. 그러므로 *p2의 값이 상수, p2는 수정 가능하다.

세번째

    int* const p3 = &a;
   //p3 = &b;
   /*
const.c: In function 'main':
const.c:16:8: error: assignment of read-only variable 'p3'
    p3 = &b;
       ^    
   */
   *p3 = 100;

const가 p3에 걸리는 case이다. 그러므로 p3가 상수여서 참조하는 값을 바꿀 수는 없으나 *p3의 값은 수정 가능하다.

일반적으로 const는 맨 앞에 붙이는 것을 선호한다고 한다.

'언어, git > C++' 카테고리의 다른 글

복사 생성자  (0) 2017.11.19
가상함수?  (0) 2017.11.19

+ Recent posts