C - 这 2 个常量是什么意思



code:

const char * const key;

上面的指针中有 2 个常量,我第一次看到这样的事情。

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

任何人都可以帮助解释这一点吗?


@Update:

我写了一个程序来证明答案是正确的。

#include <stdio.h>
void testNoConstPoiner() {
    int i = 10;
    int *pi = &i;
    (*pi)++;
    printf("%dn", i);
}
void testPreConstPoinerChangePointedValue() {
    int i = 10;
    const int *pi = &i;
    // this line will compile error
    // (*pi)++;
    printf("%dn", *pi);
}

void testPreConstPoinerChangePointer() {
    int i = 10;
    int j = 20;
    const int *pi = &i;
    pi = &j;
    printf("%dn", *pi);
}
void testAfterConstPoinerChangePointedValue() {
    int i = 10;
    int * const pi = &i;
    (*pi)++;
    printf("%dn", *pi);
}
void testAfterConstPoinerChangePointer() {
    int i = 10;
    int j = 20;
    int * const pi = &i;
    // this line will compile error
    // pi = &j
    printf("%dn", *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("%dn", *pi);
}
int main(int argc, char * argv[]) {
    testNoConstPoiner();
    testPreConstPoinerChangePointedValue();
    testPreConstPoinerChangePointer();
    testAfterConstPoinerChangePointedValue();
    testAfterConstPoinerChangePointer();
    testDoublePoiner();
}

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

第一个常量告诉你不能改变*keykey[i]

以下行无效

*key = 'a';
*(key + 2) = 'b';
key[i] = 'c';

第二个常量告诉你不能改变key

以下行无效

key = newkey;
++key;

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


添加更多详细信息。

  1. const char *key:您可以更改键,但不能更改键指向的字符。
  2. char *const key:您不能更改键,但可以通过键指向字符
  3. const char *const key :您不能更改键以及指针字符。

const [type]*表示它是一个不更改指向值的指针。 [type]* const意味着指针本身的值不能改变,即它一直指向相同的值,类似于 Java final 关键字。

最新更新