简体   繁体   English

“volatile const int a”与“const volatile int a”?

[英]"volatile const int a" vs "const volatile int a"?

I understood that if we use volatile and const together to a variable indicates that the variable value cannot be changed inside the scope of the code, but can be changed by outside scope — for example, hardware interaction with the variable a .我的理解是,如果我们将volatileconst一起用于变量,则表示变量值不能在代码范围内更改,但可以通过外部范围更改 - 例如与变量a硬件交互。

But what is the difference between the syntax volatile const int a and const volatile int a ?但是语法volatile const int aconst volatile int a什么区别?

Modifier order doesn't matter when no pointers are involved.当不涉及指针时,修饰符顺序无关紧要。 Your two examples are equivalent.你的两个例子是等价的。

If pointers are involved, the order matters only relative to the name of the core type and the * (s).如果涉及指针,顺序仅与核心类型的名称和* (s) 有关。 For a variable declaration with placeholders for modifiers A, B, C and D:对于带有修饰符 A、B、C 和 D 的占位符的变量声明:

<A> int <B> * <C> * <D>

location A or B modifies the int ( int const and const int mean the same thing), while location C affects the first * (the second level of indirection), and location D affects the second * (the first level of indirection).位置AB修改intint constconst int意思相同),而位置C影响第一个* (第二级间接),位置D影响第二个* (第一级间接)。

So:所以:

unsigned int * volatile * const x;

means that:意思是:

  1. You can't reassign x itself (but you can reassign *x or **x )您不能重新分配x本身(但您可以重新分配*x**x
  2. *x is volatile (the compiler can't optimize out reads or writes to *x , and can't reorder them relative to other volatile accesses) *xvolatile的(编译器无法优化对*x的读取或写入,并且不能相对于其他volatile访问重新排序它们)
  3. **x is unsigned (but neither volatile nor const , though *x being volatile will cause some aspects of volatile to be applied, simply because it's not allowed to cache *x , and therefore can't cache **x either; if your code explicitly cached though, eg unsigned int *starxcopy = *x; , then worked with *starxcopy , *starxcopy would be able to cache the pointed-to value, because the value itself is not volatile ) **xunsigned的(但既不是volatile也不是const ,尽管*xvolatile会导致应用volatile的某些方面,仅仅是因为它不允许缓存*x ,因此也不能缓存**x ;如果你虽然显式缓存的代码,例如unsigned int *starxcopy = *x; ,然后使用*starxcopy*starxcopy将能够缓存指向的值,因为值本身不是volatile

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

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