1

This is the code to swap 2 numbers and it works fine. But I'm curious about the "&" in front of x1 and x2 in the swap function. My code couldn't work before I added that two. What does that "&" do?

#include<iostream>
using namespace std;

void swap(int &x1,int &x2){
    int x = x1;
    x1 = x2;
    x2 = x;
}

int main(){
    int n1 , n2;
    cin >> n1 >> n2;

    swap(n1,n2);
    cout<<n1<<" "<<n2;

    return 0;   
}
Joe Jung
  • 19
  • 5

1 Answers1

0

In this function:

void swap(int &x1,int &x2)

the & means its a reference to the argument passed in. Changing these variables will change the arguments at the call site.

In this function:

void swap(int x1,int x2)

a copy of the arguments is made. Changing these variables will not change the arguments at the call site.

This is the case even without functions. e.g.

int a = 42;
int &b = a;
b = 5;  // now a is also 5
cigien
  • 57,834
  • 11
  • 73
  • 112