r/cpp • u/pavel_v • Apr 21 '26
Sure, xor’ing a register with itself is the idiom for zeroing it out, but why not sub?
https://devblogs.microsoft.com/oldnewthing/20260421-00/?p=112247
140
Upvotes
61
u/dlnnlsn Apr 21 '26
Today I learned that xor and sub execute in the same number of cycles. I would have guessed that xor is faster because the bits are independent of each other. (Like sub/add is doing a bunch of xors, *and* accounting for carry bits, right?)
31
u/Progman3K Apr 21 '26
Raymond Chen is a national treasure! He explains so well and clearly, you always learn and retain
45
u/v_maria Apr 21 '26
i think its basically tradition at this point
8
u/richardxday Apr 21 '26
I always thought that it was because you knew that xor would always work on every platform without side effects. sub might use the carry or update the carry so isn't fire-and-forget when writing code.
19
u/Sniffy4 Apr 21 '26
today i learned that 'godbolt' is someone's real name
3
u/Impossible_Box3898 Apr 25 '26
Because sub changes status registers while xor does not.
2
u/MistakeIndividual690 Apr 21 '26
SUB works too. I’ve seen that plenty as well
2
u/Causeless Apr 21 '26
I do wonder if perhaps it would’ve been better for pipelining at some point, as an xor was generally a rarer operation than sub. It seems like it could potentially give the instruction pipeliner more leeway in typical cases, though given Raymond Chen doesn’t mention it I’d imagine that isn’t related.
2
u/nacaclanga Apr 23 '26
My guess is that xor is more explicit (since sub is used for other purposes much more) and in theory xor is a simpler ALU operation (in practise they are mostly the same).
2
u/arthurno1 Apr 23 '26
I have been reading Raymond's blog since he published the book, and still I have yet to see a single blog post of his where I didn't learn something! Amazing.
3
u/VictoryMotel Apr 21 '26 edited Apr 21 '26
Sub might reset carry registers.
Also they might use different paths so it might not take up a execution path that could do integer math, but I don't know enough about either to say for sure.
1
u/kiner_shah Apr 22 '26
I wonder why isn't there an instruction for resetting register. They could have made one with the name
rstr, for example. The use could have beenrstr eax.-1
u/SyntheticDuckFlavour Apr 22 '26
subis basicallyxorwith extra steps-5
u/ern0plus4 Apr 21 '26
SUB modifies Carry Flag, XOR/EOR does not (true for all archs).