What is the output of the following program?
#include <iostream>
usingnamespace std;
void one(int x, int& y);
void two(int& s, int t);
int main()
{
int u = 1;
int v = 2;
one(u, v);
cout << u << " " << v << endl;
two(u, v);
cout << u << " " << v << endl;
return 0;
}
void one(int x, int& y)
{
int a;
a = x;
x = y;
y = a;
}
void two(int& s, int t)
{
int b;
b = s - t;
s = t + b + 2;
t = 4 * b;
}
In the first function, one, you swap the variables in theory. However in reality you only copied u to v because of the reference. At the end of 'one' u and v will be equal.
In the second function b become 0 because of the results of the first. So what is set to s is 3 because of the sum of s = 1 + 0 +2.
A reference of the variable uses the variable at the starting point and doesn't copy the variable like it would for the non-referenced ones.