> 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/coding_practice_questions/moderate/number-swapper.md).

# Number Swapper

**16.1 Number Swapper:** Write a function to swap a number in place (that is, without temporary variables).

* Notes:
  * Math is fun!

```cpp
// extra space
void swap(int *a, int *b) {
    int temp = *(a);
    *(a) = *(b);
    *(b) = temp;
}

// not safe
void swap2(int *a, int *b) {
    *(a + 1) = *(b);
    *(b) = *(a);
    *(a) = *(a + 1);
}

// safe and inplace
void swap3(int *a, int *b) {
    *(a) = *(a)+*(b);
    *(b) = *(a)-*(b);
    *(a) = *(a)-*(b);
}

int main() 
{
    int a, b;
    a = 1; b = 2;
    swap(&a, &b);
    cout << a << " " << b << endl;

    //swap2(&a, &b);
    //cout << a << " " << b << endl;

    a = -1; b = 2;
    swap3(&a, &b);
    cout << a << " " << b << endl;

}
```
