re: How can you swap two variables without using a third? VIEW POST

VIEW PARENT COMMENT VIEW FULL DISCUSSION

If that's the case, then why swap at all?

Sorting functions. So you can write something simple like

// at this point in the sort, we know we must
// swap x with some other value
if a[x] < a[y] {
     swap(&a[x], &a[y])
} else {
     swap(&a[x], &a[z]) // a[x] and a[z] may be the same value
}

Which would be inefficient, thus not recommended.

The function usually gets inlined anyway (depending on your compiler) and if it starts with if x == y { return } then it just compiles to if x != y { /* swap x and y */ }

In fact, might as well use a temporary variable at that point if you're expecting for compiler optimizations :shrug:. At that point they'd just become temporary registers and wouldn't have anything in memory, and a single xchg call

You could just write the registers yourself then...

code of conduct - report abuse