简体   繁体   English

将指向具有 volatile 成员的结构的指针作为 function 参数传递

[英]Passing a pointer to a struct with a volatile member as a function argument

If I have a structure with some of the members being volatile but not all and I pass a pointer to this structure as a function argument, would the compiler prevent optimization to those members within the functions or do I have to declare the pointer as volatile as well?如果我有一个结构,其中一些成员是 volatile 但不是全部,并且我将指向该结构的指针作为 function 参数传递,编译器是否会阻止对函数中的这些成员进行优化,或者我是否必须将指针声明为 volatile出色地?

typedef struct {
    volatile uint16_t reg1;
    volatile uint16_t reg2;
    const uint32_t speed;
    uint8_t error;
}uart;

void uartInitialize(uart *const hdlPtr);
//void uartInitialize(volatile uart *const hdlPtr); is this required?

Short answer: No need to add volatile on hdlPtr.简短回答:无需在 hdlPtr 上添加 volatile。

Long Answer: Unless the hdlPtr can be changed in some unexpected way, there is no need to declare it volatile.长答案:除非可以以某种意想不到的方式更改 hdlPtr,否则无需将其声明为 volatile。 Given that it's being local to the function, it can not be changed by anything other than the uartInitialize.鉴于它是 function 本地的,它不能被 uartInitialize 以外的任何东西更改。 Given that you declared it 'const', it can not be changes by the uartInitialize itself.鉴于您将其声明为“const”,因此 uartInitialize 本身不能对其进行更改。

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

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