c - what does this 2 const mean?

2019-01-27 07:37发布

code:

const char * const key;

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

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

Anyone can help to explain this?


@Update:

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\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();
}

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

2条回答
ら.Afraid
2楼-- · 2019-01-27 07:53

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

Following lines are invalid

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

Second const tells that you can not change key

Following lines are invalid

key = newkey;
++key;

Also check how to read this complex declaration


Adding more details.

  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.
查看更多
放我归山
3楼-- · 2019-01-27 07:54

const [type]* means that it's a pointer that does not change the pointed value. [type]* const means that the value of the pointer itself cannot change, ie, it keeps pointing to the same value, akin to the Java final keyword.

查看更多
登录 后发表回答