c - what does this 2 const mean?(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;
同时查看如何阅读这个复杂的声明
添加更多细节.
const char *key:可以改变key,但不能改变key指向的字符.char *const key:不能改变key,但可以改变key指向的字符const char *const key:你不能改变key和pointer chars.
const char *key: you can change key but can not change the chars pointed by key.char *const key: You can not change key but can the chars pointed by keyconst char *const key: You can not change the key as well as the pointer chars.
这篇关于c - 这个 2 const 是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:c - 这个 2 const 是什么意思?
- 使用 __stdcall & 调用 DLLVS2013 中的 GetProcAddress() 2021-01-01
- 哪个更快:if (bool) 或 if(int)? 2022-01-01
- 从父 CMakeLists.txt 覆盖 CMake 中的默认选项(...)值 2021-01-01
- 将函数的返回值分配给引用 C++? 2022-01-01
- OpenGL 对象的 RAII 包装器 2021-01-01
- 如何提取 __VA_ARGS__? 2022-01-01
- 将 hdc 内容复制到位图 2022-09-04
- GDB 不显示函数名 2022-01-01
- XML Schema 到 C++ 类 2022-01-01
- DoEvents 等效于 C++? 2021-01-01
