-4

This swap function is fully functional except when the input is two arrays with the same values:

void permuter(int* a, int* b) {
    *a = *a + *b;
    *b = *a - *b;
    *a = *a - *b;
}

int main(void) {
    int i[0];
    int j[0];
    i[0] = 5;
    j[0] = 5;
    permuter(&j[0], &i[0]);
    return 0;
}

using printf(); i[0] = 0 and j[0] = 0.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Loukil-M
  • 37
  • 5
  • 7
    Your two arrays have size 0, so your code is undefined behavior. The swap would work unless both pointers are the same. But there is no reason to swap this way. – interjay Oct 25 '19 at 23:42
  • @interjay Even with bigger arrays, the problem is still there. Will just swap using a temporary in the future as adviced by the answer. – Loukil-M Oct 25 '19 at 23:45
  • 2
    You might also want to consider what happens if `permuter()` is passed two equal pointers - the result is probably not what you expect. Also, if any of the additions or subtractions overflow, the behaviour is undefined. The conventional way, using a temporary,. exhibits neither problem. – Peter Oct 26 '19 at 00:47
  • Possible duplicate of [What is the difference between two different swapping function?](https://stackoverflow.com/questions/58462258/what-is-the-difference-between-two-different-swapping-function) – Steve Summit Oct 26 '19 at 01:23

1 Answers1

6

This is a common problem with clever swaps (see also: XOR swap). Do it the straightforward way, with a temporary!

int t = *a;
*a = *b;
*b = t;

In practice, you could probably check that the pointers are different to avoid this problem, but *a + *b still has undefined behaviour on overflow and there’s just no reason to have to worry about that.

Ry-
  • 218,210
  • 55
  • 464
  • 476