C 添加常量的正确方法是什么?

C 添加常量的正确方法是什么?,c,constants,C,Constants,我正在寻找一个关于如何使用const添加传统保护的规则 例如: int** p1 = ...; int** const p2=p1; // Legal int* const * const p3=p1; // Legal int* const * const p4=p3; // Legal const int* const * const p5=p3; // Error int*** cube1= &p1; int* const ** cube2=cube1; // Error and

我正在寻找一个关于如何使用const添加传统保护的规则

例如:

int** p1 = ...;
int** const p2=p1; // Legal
int* const * const p3=p1; // Legal
int* const * const p4=p3; // Legal
const int* const * const p5=p3; // Error

int*** cube1= &p1;
int* const ** cube2=cube1; // Error
and so on...

对于指针转换中的常量正确性规则,对于非数组数据类型
T
,C语言支持从类型
T*
到类型
常量T*
的隐式转换。这是C语言支持的唯一“const-protecting”隐式转换

换句话说,如果
T
U
是相同的非数组类型,则支持从
T*
const U*
的转换。如果
T
U
不同,则隐式转换无效(即使
T
U
之间的差异只是一些额外的常量限定符)

简单来说,只允许在最内部的
*
之后添加
常量。不允许在任何更深层次的间接寻址中添加
const
。这就是为什么带有
p5
cube
的行无法编译的原因

int *p = 0;
const int *cp = p; // OK: `const` is added after the first `*`

int **pp = 0;
const int *const *cpp = pp; // Error: a "deep" `const` added 
有时在代码中,您可能需要绕过这些限制,在更深层的间接寻址中添加一些额外的
const
。在这种情况下,您别无选择,只能使用显式强制转换

int **pp = 0;
const int *const *cpp = (const int *const *) pp;  

S.C++将这些限制放宽,创造了更为合理的系统的正确性规则。唉,C从来没有朝这个方向迈出过任何一步。

const
通常适用于它左侧定义的值

例如:

int const *ptr = &val;
在上面的代码片段中,
const
属于
int
,而不是
*ptr

如果将
*
移到
const
后面,它将使
ptr
成为常量指针

int *const ptr = &val;
现在
const
属于指针,而不是
int

现在看另一个例子

const int *ptr = &val;

只有当语句最左侧有一个
常量时,它才会应用于语句右侧的任何内容,在上面的代码段中,它是
int

“如何添加传统保护的规则”取决于您试图实现的保护。只有你知道你需要保护什么,不保护什么。嗨,谢谢你的快速回答!问题-为什么即使我在最内部的
*
后面添加了const,但
int*const**cube2=cube1
仍然不起作用?@StavAlfi:“最内部的
*
”我指的是最右边的
*
。在本例中,您从内部在第二个
*
之后添加了
const
。这不是最内在的。什么是“righmost
*
”?@StavAlfi我的意思是“最右边的”。在本例中-最接近所声明的标识符。感谢您提供的信息,但我不知道它如何回答我的问题。如果我的问题不够清楚的话,我很抱歉。我正在寻找一些关于如何找到当前放置const的位置的指南。