C 中这些声明有什么区别?
在 C 和 C++ 中,以下声明有何作用?
const int * i;
int * const i;
const volatile int ip;
const int *i;
上述声明是否有错误?
如果不是的话它们之间的含义和区别是什么?
上述声明有哪些有用的用途(我的意思是在什么情况下我们必须在 C/C++/嵌入式 C 中使用它们)?
In C and C++ what do the following declarations do?
const int * i;
int * const i;
const volatile int ip;
const int *i;
Are any of the above declarations wrong?
If not what is the meaning and differences between them?
What are the useful uses of above declarations (I mean in which situation we have to use them in C/C++/embedded C)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
const int * i;
i
是指向常量整数的指针。i
可以更改为指向不同的值,但i
所指向的值无法更改。int * const i;
i
是指向非常量整数的常量指针。i
指向的值可以更改,但i
不能更改为指向不同的值。const volatile int ip;
这个有点棘手。
ip
是const
的事实意味着编译器不会让您更改ip
的值。 然而,理论上它仍然可以被修改,例如通过获取它的地址并使用const_cast
运算符。 这是非常危险的,也不是一个好主意,但这是允许的。易失性
限定符指示任何时候ip
被访问时,它应该总是从内存中重新加载,即它不应该被缓存在寄存器中。 这会阻止编译器进行某些优化。 当您有一个可能被另一个线程修改的变量,或者您正在使用内存映射 I/O,或者其他可能导致编译器行为的类似情况时,您需要使用 volatile 限定符可能不会期待。 在同一个变量上使用const
和volatile
是相当不寻常的(但合法)——您通常会看到一个而不是另一个。const int *i;
这与第一个声明相同。
const int * i;
i
is a pointer to constant integer.i
can be changed to point to a different value, but the value being pointed to byi
can not be changed.int * const i;
i
is a constant pointer to a non-constant integer. The value pointed to byi
can be changed, buti
cannot be changed to point to a different value.const volatile int ip;
This one is kind of tricky. The fact that
ip
isconst
means that the compiler will not let you change the value ofip
. However, it could still be modified in theory, e.g. by taking its address and using theconst_cast
operator. This is very dangerous and not a good idea, but it is allowed. Thevolatile
qualifier indicates that any timeip
is accessed, it should always be reloaded from memory, i.e. it should NOT be cached in a register. This prevents the compiler from making certain optimizations. You want to use thevolatile
qualifier when you have a variable which might be modified by another thread, or if you're using memory-mapped I/O, or other similar situations which could cause behavior the compiler might not be expecting. Usingconst
andvolatile
on the same variable is rather unusual (but legal) -- you'll usually see one but not the other.const int *i;
This is the same as the first declaration.
可以这么说,您从右到左阅读 C/C++ 中的变量声明。
他们每个人都有自己的目的。 任何 C++ 教科书或半像样的资源都会对每个内容都有解释。
You read variables declarations in C/C++ right-to-left, so to speak.
They each have their own purposes. Any C++ textbook or half decent resource will have explanations of each.