Search code examples
cvolatileunions

What are the semantics of unions with both volatile and nonvolatile members?


More specifically, I have (simplified) the following:

union foo
    {
    volatile int bits;
    char data[sizeof(int)*CHAR_BIT];
    }

If I never access the first sizeof(int) items of data, can i rely on bits working as expected?


Solution

  • Basically marking one of the field of the structure as volatile is correct. But you have to remember what volatile keyword does. It tells the compiler to not optimize access to a variable. Value is always read from memory, not from its copy in register.

    As you write in comment, you are trying to make memory allocation thread safe. Unfortunately volatile doesn't guarantee that you can access it from multiple threads. If you are using 8bit CPU, access to integer value is not atomic operation so your program will not work correctly.