Optimizing compiler can rearrange memory access and CPU can execute instructions out of order.
The question is: will separating statements with comma operator guarantee exact order of execution? Or the only way is using memory barriers (which are tricky and non-standart)?
If it won't, than what exactly is guaranted about order of execution of comma separated statements?
The comma operator guarantees that the left side of the expression is evaluated before the right side of the expression within one thread. When the results are stored into memory is entirely unrelated to evaluation order, though, and requires some form of synchronization, e.g. memory barriers.
The comma operator is no different from simply two statements separated by ; in this respect
The language specifies the semantics of the operator, but the compiler/CPU can choose how they want to implement it. If they can do things out-of-order they are free to, as long as they can prove that the result will be the same as in-order. And they do, often.
If you want guarantees about the actual order for some reason, then you'll have to check your compiler and CPU documentation for how to enforce it. That might mean turning off optimizations, using extra keywords like volatile, use memory fences, etc. However, unless you absolutely positively need in-order, let the compiler and CPU do their thing and give you extra performance at no extra cost to you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With