C语言 可变结构语义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2044565/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Volatile Struct Semantics
提问by vicatcu
Is it sufficient to declare an instance of a structure-typed variable as volatile (if its fields are accessed in re-entrant code), or must one declare specific fields of the structure as volatile?
将结构类型变量的实例声明为 volatile 是否足够(如果在可重入代码中访问其字段),或者是否必须将结构的特定字段声明为 volatile?
Phrased differently, what are the semantic differences (if any) between:
换句话说,以下之间的语义差异(如果有的话)是什么:
typdef struct {
uint8_t bar;
} foo_t;
volatile foo_t foo_inst;
and
和
typedef struct{
volatile uint8_t bar;
} foo_t;
foo_t foo_inst;
I recognize that declaring a pointer-typed variable as volatile (e.g. volatile uint8_t * foo) merely informs the compiler that the address pointed-to by foo may change, while making no statement about the values pointed to by foo. It is unclear to me whether an analogy holds for structure-typed variables.
我认识到将指针类型变量声明为 volatile(例如 volatile uint8_t * foo)只是通知编译器 foo 指向的地址可能会改变,而没有声明 foo 指向的值。我不清楚结构类型变量是否有类比。
回答by R Samuel Klatchko
In your example, the two are the same. But the issues revolve around pointers.
在您的示例中,两者是相同的。但问题围绕着指针展开。
First off, volatile uint8_t *foo;tells the compiler the memory being pointed to is volatile. If you want to mark the pointer itself as volatile, you would need to do uint8_t * volatile foo;
首先,volatile uint8_t *foo;告诉编译器指向的内存是易失性的。如果要将指针本身标记为 volatile,则需要执行以下操作uint8_t * volatile foo;
And that is where you get to the main differences between marking the struct as volatile vs marking individual fields. If you had:
这就是将结构标记为 volatile 与标记单个字段之间的主要区别的地方。如果你有:
typedef struct
{
uint8_t *field;
} foo;
volatile foo f;
That would act like:
那会像这样:
typedef struct
{
uint8_t * volatile field;
} foo;
and not like:
而不喜欢:
typedef struct
{
volatile uint8_t *field;
} foo;
回答by Alon
if you declare a structure with volatile then all its members will also be volatile
如果你用 volatile 声明一个结构,那么它的所有成员也将是 volatile

