DEV Community

Discussion on: Swapping Numbers Without a Temporary Variable in C using XOR like a pro.

Collapse
 
pauljlucas profile image
Paul J. Lucas

You neglected to say why you'd want to do this. "Without using a temporary" isn't a goal. Is using XOR actually more performant? Did you profile it?

Collapse
 
seamoonpandey profile image
Seamoon Pandey

Swapping variable with XOR is a classic programming trick.
Regarding performance, XOR swapping is often considered more efficient than using a temporary variable because it involves only three bitwise XOR operations, which are typically faster than assignment operations and memory accesses involved in using a temporary variable.

Collapse
 
pauljlucas profile image
Paul J. Lucas

Yes, I know about XOR. I gave my comment to point out that you don't tell the reader in general as part of your article why you'd do it.

That aside, unless it's part of a hot-code path, it doesn't matter. You should always profile before doing (premature) optimization.