问题描述
执行 int const * a
和 const int * a
表示 a是指向常量的整数指针值和 a是指向常量地址的指针,还是相反?
Do int const *a
and const int *a
mean that "a is a integer pointer to a constant value" and "a is a pointer to a constant address", respectively , or is it viceversa?
这是在采访中问我的。在阅读了很多相同的内容之后,我对此仍然感到非常困惑。
This was asked to me in an interview. After reading a lot about the same I am still very much confused regarding it.
推荐答案
-
const int * a
-a
是可写的(可以指向其他内容),* a
是不可写的(无法写指向的东西) -
int const * a
-与上面相同 -
int * const a
-a
是不可写的(无法指向* a
是可写的(可以写指向的东西) -
const int * const a
-a
和* a
都不可写 -
int const * const a
-与上面相同 const int *a
-a
is writable (can point to a different thing),*a
is not writable (cannot write to pointed-to thing)int const *a
- same as aboveint * const a
-a
is not writeable (cannot point to a different thing),*a
is writable (can write to pointed-to thing)const int * const a
- neithera
nor*a
are writableint const * const a
- same as above
如果您将前两种情况读为
If you read the first two cases as
const int (*a)
int const (*a)
很明显, const
正在修改 int
类型说明符;我们指向的是恒定整数。
it's clear that the const
is modifying the int
type specifier; we're pointing to a constant integer.
如果您将第三种情况读为
If you read the third case as
int (* const a)
然后 const
正在修改指针声明符 * a
;我们有一个指向整数的常量指针。
then the const
is modifying the pointer declarator *a
; we have a constant pointer to an integer.
然后您将最后两种情况读为
Then you read the final two cases as
(const int) (* const a)
(int const) (* const a)
然后显然,我们有一个 const
修改了类型说明符,另一个修改了指针,所以我们有一个 constant指针指向恒定整数。
then it's clear that we have one const
modifying the type specifier and the other modifying the pointer, so we have a constant pointer to a constant integer.
这篇关于指向地址的常量指针或指向值的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!