Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comma operator and out of order execution

Tags:

c++

c

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?

like image 817
Amomum Avatar asked Feb 03 '26 17:02

Amomum


2 Answers

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.

like image 98
Dietmar Kühl Avatar answered Feb 06 '26 07:02

Dietmar Kühl


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.

like image 34
Adam Avatar answered Feb 06 '26 06:02

Adam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!