DEV Community

Discussion on: How can you swap two variables without using a third?

Collapse
 
joshichinmay profile image
Chinmay Joshi

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

Thread Thread
 
dean profile image
dean

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
}
Thread Thread
 
tux0r profile image
tux0r

Which would be inefficient, thus not recommended.

Thread Thread
 
dean profile image
dean

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

Thread Thread
 
tux0r profile image
tux0r

You could just write the registers yourself then...