Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
218 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 Reply

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...