Search code examples
cpointersstructvolatile

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?

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?

Solution

  • Short answer: No need to add volatile on hdlPtr.

    Long Answer: Unless the hdlPtr can be changed in some unexpected way, there is no need to declare it volatile. Given that it's being local to the function, it can not be changed by anything other than the uartInitialize. Given that you declared it 'const', it can not be changes by the uartInitialize itself.