Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

c++ - c - what does this 2 const mean?

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...