Why is my function wrong?

Hello,

Practice working with functions and I don't understand why I'm getting this wrong.

1)I'm not understanding why the output for both functions is
1 1
3 1

for instance, i get a result of 2 1 for function "one". I'm assuming it has to do with the pass by reference of the parameters?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
What is the output of the following program?

#include <iostream>
using namespace 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;
}



Thank you very much!
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.
Topic archived. No new replies allowed.