c - 这个 2 const 是什么意思? [英] c - what does this 2 const mean?

查看:40
本文介绍了c - 这个 2 const 是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码:

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.

这篇关于c - 这个 2 const 是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆