Reference Parameter help/confusion

I am new to Reference Parameters, and am in confusion on why my program is displaying a different output than I expected. I was playing around with this particular program and mixing reference functions and parameter functions.

As you can see, the last parameter is not a reference, which is the "int c". My goal was to return this variable to the main and display it, along with the two others being a reference and simple displaying that in the cout statement.

I expected to see "4", and "8", and 12". Instead I am getting "8" and "16" and "12". In the cout statement on line 20, I couted the "duplicate(x, y, z)" just for the return value. Funny enough, I got the "12" right but everything else seems weird.

Again, this is not really a program, but just me playing around with references and parameters together. Thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;

int duplicate(int& a, int& b, int c)
{
	a *= 2;
	b *= 2;
	c *= 2;

	return c;
}

int main()
{
	int x = 2, y = 4, z = 6, que;

	duplicate(x, y, z);
					
	cout << x << " and " << y << " and " << duplicate(x, y, z) << endl;
	

	return 0;
}
You call duplicate() twice.
closed account (SECMoG1T)
hello.

1
2
3
4
5
6
7
8
9
10
11
int main()
{
	int x = 2, y = 4, z = 6, que;

	z =duplicate(x, y, z);///you should do this

	///cout << x << " and " << y << " and " << duplicate(x, y, z) << endl;///calling the function twice
    cout << x << " and " << y << " and " << z << endl;

	return 0;
}
cout << x << " and " << y << " and " << duplicate(x, y, z) << endl;

The order of events in this is NOT from left to right. duplicate is being called before x and y are being sent to cout.

In C++17, the rules change, but you're not using a C++17 compiler (I expect).

Topic archived. No new replies allowed.