Is the order of writes to separate members of a volatile struct guaranteed to be preserved?

c

They will not be reordered.

C17 6.5.2.3(3) says:

A postfix expression followed by the . operator and an identifier designates a member of a structure
or union object. The value is that of the named member, 97) and is an lvalue if the first expression is
an lvalue. If the first expression has qualified type, the result has the so-qualified version of the type
of the designated member.

Since data has volatile-qualified type, so do data.bar and data.foo. Thus you are performing two assignments to volatile int objects. And by 6.7.3 footnote 136,

Actions on objects so declared [as volatile] shall not be “optimized out” by
an implementation or reordered except as permitted by the rules for evaluating expressions.

A more subtle question is whether the compiler could assign them both with a single instruction, e.g., if they are contiguous 32-bit values, could it use a 64-bit store to set both? I would think not, and at least GCC and Clang don’t attempt to.

Leave a Comment