const 与指针

基本类型 / 指针

//const 在 * 右侧锁定指针,
//在左侧锁定值
int a = 1;
int b = 2;

//指向 const 的指针:不能通过它修改值
const int *pValue = &a;
//*pValue = 10; //<-Error
pValue = &b;
//*pValue is 2

//const 指针:不能指向另一个变量
int *const pFixed = &a;
*pFixed = 10;
//pFixed = &b; //<-Error
//a is 10

//两者都被锁定
const int *const pBoth = &b;
//*pBoth is 2
//*pBoth = 20; //<-Error
//pBoth = &a; //<-Error

//参数中的 const:函数承诺只读取
int sum(const int *numbers, size_t count) {
    int total = 0;
    for (size_t i = 0; i < count; i++) {
        total += numbers[i];
    }
    return total;
}

int numbers[] = {1, 2, 3};
int total = sum(numbers, 3);
//total is 6

printf("*pValue is %d\n", *pValue);
printf("a is %d\n", a);
printf("*pBoth is %d\n", *pBoth);
printf("total is %d\n", total);