可以通过在数据类型之前或之后添加const关键字来定义常量变量。const修饰符使变量成为只读,并且只能在声明时赋值。

const int var = 5;   /* recommended order */
int const var2 = 10; /* alternative order */

常量指针

对于指针,const可以以两种方式使用。首先,常量指针意味着它不能指向另一个位置。

int myPointee;
int* const p = &myPointee; /* constant pointer */

其次,常量指针意味着指向的变量不能通过此指针修改。

const int* q = &var; /* constant pointee */

将指针和指针对象都声明为常量。

const int* const r = &var; /* constant pointer & pointee */

常数参数

函数参数可以标记为常量,以防止函数更新它们。

void foo(const int* x) {
  if (x != NULL) {
    int i = *x; /* allowed */
    *x = 1;     /* compile-time error */
  }
}