Home > Enterprise >  Both variables end up having same value when trying to swap them using references
Both variables end up having same value when trying to swap them using references

Time:11-28

I'm trying to swap two variables' contents. I did it just fine using pointers. But trying to implement it using references is not working.

#include <iostream>

//Implementing a reference based swap
void RefSwap(int& x, int& y)
{
    int extra;
    extra = x; //automatically de-referenced
    x = y;
    y = extra;
}

int main()
{
    int a = 3, b = 10;
    int& ref_a = a, ref_b = b;  //refs don't actually exist in memory, they act like aliases

    RefSwap(ref_a, ref_b);
    std::cout << a << " " << b << std::endl;
}

My output:

10 10

Expected output:

10 3

Using VS Community 2022

CodePudding user response:

int& ref_a = a, ref_b = b;  

This is

int& ref_a = a;
int ref_b = b;  

Not:

int& ref_a = a;
int& ref_b = b;  

Change:

int& ref_a = a, ref_b = b;  

To:

int& ref_a = a;
int& ref_b = b;  

will produce the correct result.

  • Related