Pass-by Reference

When using pass-by reference. When a function is called in the main in a different order, will it affect the output of the integers.
Example:

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

void mystery(int&, int, int&);

int main()
{
	int a = 11, b = 22, c = 33;
	
	mystery(b, c, a);
	
	cout << a << endl;
	cout << b << endl;
	cout << c << endl;
	 
}

void mystery(int& a, int b, int& c)
{
	b += a;
	
	a +=c;
	
	c -= b;
	
	b *= 10;
}



As you can see, in the main function it is labeled as mystery(b, c, a). The output of the code is -443333. I have been working on this awhile now and i'm unable the understand how that output is derived.
Last edited on
The name of the variables in main() are not "linked" to the variables in mystery(). You can see this by renaming the variables in main() or by changing the parameter names in mystery.

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
int main()
{
    int a = 11, b = 22, c = 33;
    
    mystery(b, c, a);
    // a == -44, b == 33, c == 33
    
    cout << a << endl;
    cout << b << endl;
    cout << c << endl;
     
}

void mystery(int& a, int b, int& c)
{
    /* variables in main */
    // b        c        a
    /* local variables */
    // a == 22, b == 33, c == 11

    b += a;
    // b == 55

    a +=c;
    // a == 33

    c -= b;
    // c == -44
    
    b *= 10;
    // b == 550
    // however, as b is passed by value
    // c in main() doesn't change
}
Thanks so much for your help. I spent 1h trying to understand how it worked.
Topic archived. No new replies allowed.