[英]"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
.我的理解是,如果我们将volatile
和const
一起用于变量,则表示变量值不能在代码范围内更改,但可以通过外部范围更改 - 例如与变量a
硬件交互。
But what is the difference between the syntax volatile const int a
and const volatile int a
?但是语法volatile const int a
和const 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).位置A
或B
修改int
( int const
和const int
意思相同),而位置C
影响第一个*
(第二级间接),位置D
影响第二个*
(第一级间接)。
So:所以:
unsigned int * volatile * const x;
means that:意思是:
x
itself (but you can reassign *x
or **x
)您不能重新分配x
本身(但您可以重新分配*x
或**x
)*x
is volatile
(the compiler can't optimize out reads or writes to *x
, and can't reorder them relative to other volatile
accesses) *x
是volatile
的(编译器无法优化对*x
的读取或写入,并且不能相对于其他volatile
访问重新排序它们)**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
) **x
是unsigned
的(但既不是volatile
也不是const
,尽管*x
是volatile
会导致应用volatile
的某些方面,仅仅是因为它不允许缓存*x
,因此也不能缓存**x
;如果你虽然显式缓存的代码,例如unsigned int *starxcopy = *x;
,然后使用*starxcopy
, *starxcopy
将能够缓存指向的值,因为值本身不是volatile
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.