什么是用C这些声明有何区别? [英] What is the difference between these declarations in 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?
什么是上述声明的有效使用(我的意思是在什么情况下,我们必须用C / C ++ /嵌入式C使用它们)?
What are the useful uses of above declarations (I mean in which situation we have to use them in C/C++/embedded C)?
推荐答案
const int的*我;
I
是一个指向常整型。 I
可以更改为指向一个不同的值,但被指向值由 I
不能改变。
i
is a pointer to constant integer. i
can be changed to point to a different value, but the value being pointed to by i
can not be changed.
为int * const的我;
I
是一个常量指针到非恒定的整数。该值指向 I
是可以改变的,但 I
不能更改指向不同的值。
i
is a constant pointer to a non-constant integer. The value pointed to by i
can be changed, but i
cannot be changed to point to a different value.
const的挥发INT IP;
这一个是棘手的一种。事实上, IP
是常量
意味着编译器不会让你改变的价值IP
。但是,它仍可以在理论上修饰,例如通过采取它的地址,并使用的const_cast
运营商。这是非常危险的,不是一个好主意,但它是允许的。在挥发性
限定词表示任何时间 IP
被访问时,它应始终从内存重新加载,也就是说,它不应该缓存在寄存器中。这prevents从使某些优化编译器。你想,当你有可能被另一个线程修改的变量使用挥发性
预选赛上,或者如果你使用内存映射I / O,或其他类似情况这可能导致行为的编译器可能不被期待的。使用常量
和挥发性
在同一个变量是相当不寻常的(但合法的) - 你通常会看到一个,但不是其他。
This one is kind of tricky. The fact that ip
is const
means that the compiler will not let you change the value of ip
. However, it could still be modified in theory, e.g. by taking its address and using the const_cast
operator. This is very dangerous and not a good idea, but it is allowed. The volatile
qualifier indicates that any time ip
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 the volatile
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. Using const
and volatile
on the same variable is rather unusual (but legal) -- you'll usually see one but not the other.
const int的*我;
这是一样的第一个声明。
This is the same as the first declaration.
这篇关于什么是用C这些声明有何区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!