-7

This is a particularly strange question, but i'm attempting to write a function that swaps the values of two integers without using references or '&'. I don't see how this is even possible. Here's what I have so far.

    void swap (int a, int b)
    {

    int temp;
    temp = a;
    a = b;
    b = temp;

    }

This, normally would be the way that I would do it, but since the integers don't permanently change, I have no idea as to how I would do this without referencing. Any suggestions?

Thanks!

2 Answers2

-2

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.

besc
  • 2,507
  • 13
  • 10
-2

There is this old trick to swap two integer-like variables without using a temporary variable:

void swap(int& a, int& b)
{
    a ^= b; 
    b ^= a; // b ^ (a ^b)  = a
    a ^= b; // (a ^ b) ^ a = b
}
Michaël Roy
  • 6,338
  • 1
  • 15
  • 19