C - 这 2 个常量是什么意思
c - what does this 2 const mean?
code:
const char * const key;
上面的指针中有 2 个常量,我第一次看到这样的事情。
我知道第一个常量使指针指向的值不可变,但是第二个常量是否使指针本身不可变?
任何人都可以帮助解释这一点吗?
@Update:
我写了一个程序来证明答案是正确的。
#include <stdio.h>
void testNoConstPoiner() {
int i = 10;
int *pi = &i;
(*pi)++;
printf("%dn", i);
}
void testPreConstPoinerChangePointedValue() {
int i = 10;
const int *pi = &i;
// this line will compile error
// (*pi)++;
printf("%dn", *pi);
}
void testPreConstPoinerChangePointer() {
int i = 10;
int j = 20;
const int *pi = &i;
pi = &j;
printf("%dn", *pi);
}
void testAfterConstPoinerChangePointedValue() {
int i = 10;
int * const pi = &i;
(*pi)++;
printf("%dn", *pi);
}
void testAfterConstPoinerChangePointer() {
int i = 10;
int j = 20;
int * const pi = &i;
// this line will compile error
// pi = &j
printf("%dn", *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("%dn", *pi);
}
int main(int argc, char * argv[]) {
testNoConstPoiner();
testPreConstPoinerChangePointedValue();
testPreConstPoinerChangePointer();
testAfterConstPoinerChangePointedValue();
testAfterConstPoinerChangePointer();
testDoublePoiner();
}
取消注释 3 个函数中的行,将得到带有提示的编译错误。
第一个常量告诉你不能改变*key
、key[i]
等
以下行无效
*key = 'a';
*(key + 2) = 'b';
key[i] = 'c';
第二个常量告诉你不能改变key
以下行无效
key = newkey;
++key;
另请查看如何阅读此复杂声明
添加更多详细信息。
-
const char *key
:您可以更改键,但不能更改键指向的字符。 -
char *const key
:您不能更改键,但可以通过键指向字符 -
const char *const key
:您不能更改键以及指针字符。
const [type]*
表示它是一个不更改指向值的指针。 [type]* const
意味着指针本身的值不能改变,即它一直指向相同的值,类似于 Java final
关键字。
相关文章:
- 常量字符*的性质是什么?
- 初始化不是整数的巨大常量多维数组的最佳方法是什么?
- C++:允许临时对象调用非常量成员函数的设计理念是什么?
- 从模块导出全局常量的正确方法是什么?
- C++ 中常量指针的目的是什么?
- 引用和指向常量的指针的用法是什么
- 不确定 c++ 中的常量函数是什么
- C++重载运算符两次,一个返回非常量引用,另一个返回常量引用,首选项是什么
- C++11标准中的核心常量表达式是什么
- 重载全常量类型的复制赋值运算符的正确方法是什么?
- 输入参数类型"常量双 *&"是什么意思?
- 常量方法指针的类型是什么
- 当我们在 c++ 中将常量整数引用分配给整数指针时,行为是什么
- C++ "const T &const" 第二个常量的含义是什么?
- 里面的常量变量是什么?
- 指向常量数组的指针的正确定义是什么
- C - 这 2 个常量是什么意思
- 返回常量指针(例如 int * const)的函数的用例是什么
- 在命名空间中定义双常量的最佳方式是什么
- 常量λ是什么意思