how to declare pointer to volatile struct

c

Solution

If you declare

extern volatile UART UART1;

Then any pointer derived from that variable will be of type `volatile UART *` and as a matter of fact your compiler should issue a warning if you try to assign it to any other type of variable.

If you wish `UART` to always be `volatile` then you can typedef it as such

typedef volatile struct {...} tagUART UART;

Or as unwind said to declare specific fields as volatile

typedef struct tagUART {
        volatile unsigned int uxmode;
        unsigned int uxsta;
        volatile unsigned int uxtxreg;
        unsigned int uxrxreg;
        unsigned int uxbrg;
} UART, *PUART;

The inline use of `volatile` i.e.

while (*(volatile int *)&a) ;

is discouraged and should only be used for variables that are normally not volatile, but have to be in this context.

Another way is to have a `union` where accessing one version is volatile another is not:

union {
    volatile UART volatile_version;
    UART normal;
};

Problem

Let's say I have the following definitions : ``` /* Generic structure of entire SFR area for each UART module */ typedef struct tagUART { unsigned int uxmode; unsigned int uxsta; unsigned int uxtxreg; unsigned int uxrxreg; unsigned int uxbrg; } UART, *PUART; /* SFR blocks for each UART module */ extern volatile UART UART1 __attribute__((__sfr__)); extern volatile UART UART2 __attribute__((__sfr__)); ``` Now if I acces the register through UART1, everything is fine, but what if I us a pointer to the structure, how should I declare it to specify the whole aera pointed to is volatile ? ``` volatile UART * hw = &UART1; ``` Is that ok ?

Original source