C语言 const char* p 和 char const* p 的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3110299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between const char* p and char const* p
提问by Pete Kirkham
Possible Duplicate:
what is the difference between const int*, const int * const, int const *
Are there any Difference between const char* p and char const* p
回答by phimuemue
const char* pis a pointer to a const char.
const char* p是一个指向 a 的指针const char。
char const* pis a pointer to a char const.
char const* p是一个指向 a 的指针char const。
Since const charand char constis the same, it's the same.
因为const char和char const是一样的,所以是一样的。
However, consider:
但是,请考虑:
char * const pis a constpointer to a (non-const) char. I.e. you can change the actual char, but not the pointer pointing to it.
char * const p是const指向(非常量)字符的指针。即您可以更改实际的字符,但不能更改指向它的指针。
回答by Pete Kirkham
Some of the words are not in the same order.
有些词的顺序不一样。
(there's no semantic difference until the const moves relative to the star)
(在常量相对于星形移动之前没有语义差异)
回答by IntelliChick
No difference, since the position of the '*' has not moved.
没有区别,因为“*”的位置没有移动。
1) const char *p - Pointer to a Constant char ('p' isn't modifiable but the pointer is)
2) char const *p - Also pointer to a constant Char
1) const char *p - 指向常量 char 的指针('p' 不可修改,但指针是)
2) char const *p - 也是指向常量 Char 的指针
However if you had something like:
char * const p - This declares 'p' to be a constant pointer to an char. (Char p is modifiable but the pointer isn't)
但是,如果您有类似的内容:
char * const p - 这将声明 'p' 为指向 char 的常量指针。(字符 p 是可修改的,但指针不是)
回答by Amardeep AC9MF
There is no functional difference between those two. The 'more precise' one is char const * pbecause the semantics are right to left.
这两者在功能上没有区别。“更精确”是char const * p因为语义是从右到左的。
回答by Alexander Gessler
There's no semantic difference, but it's a matter of coding style and readability. For complex expressions, reading from right to left works fine:
没有语义差异,但这是编码风格和可读性的问题。对于复杂的表达式,从右到左阅读效果很好:
char const ** const
char const ** const
is a const pointer to a pointer to a constant char.
是一个const pointer to a pointer to a constant char。
So char const *is more consistent in this regard. Many people, however, prefer const char*for its readibility - it is immediately clear what it means.
所以char const *在这方面比较一致。然而,许多人更喜欢const char*它的可读性——它的含义很明显。

