> For the complete documentation index, see [llms.txt](https://maksimdan.gitbook.io/interview-practice-problems/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://maksimdan.gitbook.io/interview-practice-problems/leetcode_sessions/mathematics/swap-in-place.md).

# Swap In Place

```cpp
/**
 * Write a method to swap two integers 
 * without using any extra memory.
 */

/*
Reasoning:
- <----------a-------b----------->
- Then b - a = distance(a,b)
- from b subtracting dist we get to a.
- from a adding dist we get to b.
*/

void inplace_swap(int &a, int &b)
{
    a = b - a;
    b = b - a;
    a = b + a;
}

int main()
{
    int a = 2;
    int b = 44;

    inplace_swap(a, b);
    cout << a << " " << b << endl;

    a = 344;
    b = 23;

    inplace_swap(a, b);
    cout << a << " " << b << endl;

    a = -120;
    b = 32;

    inplace_swap(a, b);
    cout << a << " " << b << endl;

    a = 23;
    b = -399;

    inplace_swap(a, b);
    cout << a << " " << b << endl;
}
```
