简体   繁体   English

这些声明在C中有什么区别?

[英]What is the difference between these declarations in C?

In C and C++ what do the following declarations do? 在C和C ++中,以下声明有什么作用?

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)? 上述声明有什么用处(我的意思是我们必须在C / C ++ / embedded C中使用它们)?

const int * i;

i is a pointer to constant integer. i是一个指向常量整数的指针。 i can be changed to point to a different value, but the value being pointed to by i can not be changed. i可以更改为指向不同的值,但是i指向的值无法更改。

int * const i;

i is a constant pointer to a non-constant integer. i是一个指向非常数整数的常量指针。 The value pointed to by i can be changed, but i cannot be changed to point to a different value. i指向的值可以更改,但i无法更改为指向不同的值。

const volatile int ip;

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 . ipconst的事实意味着编译器不会让你改变ip的值。 However, it could still be modified in theory, eg by taking its address and using the const_cast operator. 但是,它仍然可以在理论上进行修改,例如通过获取其地址并使用const_cast运算符。 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, ie it should NOT be cached in a register. volatile限定符表示任何时候访问ip ,它应该总是从内存重新加载,即它不应该缓存在寄存器中。 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. 如果您有一个可能被另一个线程修改的变量,或者您正在使用内存映射I / O或其他可能导致编译器可能不期望的行为的类似情况,您希望使用volatile限定符。 Using const and volatile on the same variable is rather unusual (but legal) -- you'll usually see one but not the other. 在同一个变量上使用constvolatile是相当不寻常的(但是合法的) - 你通常会看到一个而不是另一个。

const int *i;

This is the same as the first declaration. 这与第一个声明相同。

You read variables declarations in C/C++ right-to-left, so to speak. 你可以说从右到左的C / C ++中读取变量声明。

const int *i;  // pointer to a constant int (the integer value doesn't change)

int *const i;  // constant pointer to an int (what i points to doesn't change)

const volatile int ip;  // a constant integer whose value will never be cached by the system

They each have their own purposes. 他们每个人都有自己的目的。 Any C++ textbook or half decent resource will have explanations of each. 任何C ++教科书或半合适的资源都会有解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM