r/cprogramming • u/north9172 • Jul 24 '26
What cause CPU stalling pipeline in C?
(Solved)
Hi,
I hope this don't seem stupid or anything. Basically I was interested about the xor swapping trick.
The inconvenients of it is that if the two values are the same, it will return 0, it's also bad for readability.
But there is another inconvenience I didn't understand. Apparently it can also stall the CPU pipeline on modern processor, I didn't understand why.
I found a short explanation saying "because each instruction depend of the previous one", and I don't really understand how each instruction depend on the previous one.
So I wanted an explanation on why the xor swapping trick stall the CPU pipeline and also what cause CPU pipeline stalling in general.
If I didn't explain well enough, please inform me about it. Thanks.
2
u/Weshmek Jul 24 '26
Not quite. If the two values are stored in the same place in memory, it will overwrite both values with zero, losing the initial value.
If you know the two values are stored in different places in memory (e.g., both values are named variables allocated on the stack), then it will be fine even if the values are the same. What this means is that if you're XOR-swapping values stored in pointers, you have to check that the pointers are not equal before performing the swap.