Const Usage
const的三種用法
  • 指向const的pointer
    • usage: const type * var_name, type const * var_name
    • pointer所指到的對象是const
const int *p; // int const *p;
int a = 5;
int b = 3;

p = &a;
*p = 3; // error
p = &b; // ok
  • const pointer
    • usage: type* const var_name
    • pointer本身不能隨便指到別的變數, 但指到的變數可以修改他的值, 必須初始化
int a = 5;
int b = 3;
int * const p = &a;

*p = 3; // ok
p = &b; // error
  • 指向const 的const pointer
    • usage: const type * const var_name
    • pointer只能指向一個const, 而且不能在指向其他的變數
int a = 5;
int b = 3;
const int const *p = &a;

*p = 3; // error
p = &b; // error
c
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License