You should correct the question title. It says “using references”. That’s the opposite of what you mean, apparently.
Assuming that:
- truly no references and pointers allowed, exluding any wrapper tricks
- a runtime swap is what you want – as opposed to compile time template trickery
- no classes, because that would trivial
I can think of one utterly horrible solution. Make your ints globals.
ridiculous_swap.hpp
#ifndef RIDICULOUS_SWAP_HPP
#define RIDICULOUS_SWAP_HPP
extern int first;
extern int second;
void swap_ints();
#endif // RIDICULOUS_SWAP_HPP
ridiculous_swap.cpp
int first = 0;
int second = 0;
void swap_ints()
{
auto tmp = first;
first = second;
second = tmp;
}
main.cpp
#include "ridiculous_swap.hpp"
#include <iostream>
int main()
{
first = 23;
second = 42;
std::cout << "first " << first << " second " << second << "\n";
// prints: first 23 second 42
swap_ints();
std::cout << "first " << first << " second " << second << "\n";
// prints: first 42 second 23
}
It’s not useful for anything, but it does swap two integers without using references or pointers.