c - 这个 2 const 是什么意思?

2022-01-24 00:00:00 c constants c++ const-pointer

代码:

const char * const key;

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

There are 2 const in above pointer, I saw things like this the first time.

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

I know the first const makes the value pointed by the pointer immutable, but did the second const make the pointer itself immutable?

谁能帮忙解释一下?

@更新:

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

And I wrote a program that proved the answer is correct.

#include <stdio.h>

void testNoConstPoiner() {
    int i = 10;

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

void testPreConstPoinerChangePointedValue() {
    int i = 10;

    const int *pi = &i;

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


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

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

void testAfterConstPoinerChangePointedValue() {
    int i = 10;

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

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

    int * const pi = &i;
    // this line will compile error
    // pi = &j
    printf("%d
", *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
", *pi);
}

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

    testPreConstPoinerChangePointedValue();
    testPreConstPoinerChangePointer();

    testAfterConstPoinerChangePointedValue();
    testAfterConstPoinerChangePointer();

    testDoublePoiner();
}

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

Uncomment lines in 3 of the functions, will get compile error with tips.

推荐答案

第一个 const 告诉你不能改变 *key, key[i]

First const tells you can not change *key, key[i] etc

以下行无效

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

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

Second const tells that you can not change key

以下行无效

key = newkey;
++key;

同时查看如何阅读这个复杂的声明

添加更多细节.

  1. const char *key:可以改变key,但不能改变key指向的字符.
  2. char *const key:不能改变key,但可以改变key指向的字符
  3. const char *const key:你不能改变key和pointer chars.
  1. const char *key: you can change key but can not change the chars pointed by key.
  2. char *const key: You can not change key but can the chars pointed by key
  3. const char *const key: You can not change the key as well as the pointer chars.

相关文章