c - 这个2 const意味着什么?

Eri*_*ang 1 c c++ const const-pointer

码:

const char * const key;
Run Code Online (Sandbox Code Playgroud)

上面的指针有2个const,我第一次看到这样的东西.

我知道第一个const使指针指向的值不可变,但第二个const是否使指针本身不可变?

有人可以帮忙解释一下吗?


@Update:

我写了一个程序,证明答案是正确的.

#include <stdio.h>

void testNoConstPoiner() {
    int i = 10;

    int *pi = &i;
    (*pi)++;
    printf("%d\n", i);
}

void testPreConstPoinerChangePointedValue() {
    int i = 10;

    const int *pi = &i;

    // this line will compile error
    // (*pi)++;
    printf("%d\n", *pi);
}


void testPreConstPoinerChangePointer() {
    int i = 10;
    int j = 20;

    const int *pi = &i;
    pi = &j;
    printf("%d\n", *pi);
}

void testAfterConstPoinerChangePointedValue() {
    int i = 10;

    int * const pi = &i;
    (*pi)++;
    printf("%d\n", *pi);
}

void testAfterConstPoinerChangePointer() {
    int i = 10;
    int j = 20;

    int * const pi = &i;
    // this line will compile error
    // pi = &j
    printf("%d\n", *pi);
}

void testDoublePoiner() {
    int i = 10;
    int j = 20;

    const int * const pi = &i;
    // both of following 2 lines will compile error
    // (*pi)++;
    // pi = &j
    printf("%d\n", *pi);
}

int main(int argc, char * argv[]) {
    testNoConstPoiner();

    testPreConstPoinerChangePointedValue();
    testPreConstPoinerChangePointer();

    testAfterConstPoinerChangePointedValue();
    testAfterConstPoinerChangePointer();

    testDoublePoiner();
}
Run Code Online (Sandbox Code Playgroud)

取消注释3个函数中的行,将得到编译错误提示.

Gya*_*ain 9

首先常量是为了告诉你不能改变*key,key[i]等等

以下行无效

*key = 'a';
*(key + 2) = 'b';
key[i] = 'c';
Run Code Online (Sandbox Code Playgroud)

第二个const告诉你不能改变 key

以下行无效

key = newkey;
++key;
Run Code Online (Sandbox Code Playgroud)

另请查看如何阅读此复杂声明


添加更多细节.

  1. const char *key:您可以更改密钥但不能更改密钥指向的字符.
  2. char *const key:您无法更改密钥,但密钥可以指向字符
  3. const char *const key:您不能更改键和指针字符.