Reputation: 6503
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?
Upvotes: 3
Views: 696
Reputation: 17339
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.
Upvotes: 3
Reputation: 153895
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.
Upvotes: 7
Reputation: 41504
No, it will not. Order of execution (as measured by other threads) is guaranteed by the tools that are designed to guarantee order of execution. The comma operator is for discarding the value of the first expression, and is of limited use.
The "as if" rule is king here, and in the absence of barriers, it's construed in a single-threaded context.
Upvotes: 3