Can two sequential assignment statements in C be executed on hardware out of order?

  • A+

Given the following C program:

static char vals[ 2 ] = {0, 0};  int main() {  char *a = &vals[0]; char *b = &vals[1];  *a = 1; *b = 2;  return 0; } 

Is it possible for the hardware to actually load the value 2 into the memory location &vals[1] first, such that an interrupt routine could execute and see vals[1] == 2 and vals[0] == 0?

If this is possible, any description of the load/store operations that would result in this scenario would be much appreciated.


C doesn't run on hardware directly. It has to be compiled first.

The specifics of undefined behaviour (like unsynchronized reads of non-atomic variables) totally depend on the implementation (including compile-time reordering in the compiler, and depending on the target CPU architecture, the runtime reordering rules of the that ISA).

Reads/writes of non-atomic variables are not considered an observable side-effect in C or C++, so they can be optimized away and reordered up to the limit of preserving the behaviour of the program as a whole (except when the program has undefined behaviour- optimizations can do anything in that case even if the compiler can't "see" there will be UB when it's compiling.)

See also


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: