i need help with the unbelievable output of this program?

please explain me this program, how x value retains its original passed value i.e., 2 and y value has changed its value as 15 while returning to main()...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  #include <iostream>
using namespace std;
void Sum(int a, int b, int & c)
{
	
	a = b + c;
	b = a + c;
	c = a + b;
}
int main()
{
	int x = 2, y = 3;
	Sum(x, y, y);
	cout << x << " " << y;
	system("pause");
	return 0;
}
//Put the code you need help with here. 

output: 2,15
That's because of this right here:

void Sum(int a, int b, int ->&<- c)

That & sign is called an address-of operator. That c that you passed is not a value itself. It is a pointer to your y value. That is why the y-value changed, because the Sum function changed the y-value itself.

a = 3 + 3 = 6
b = 6 + 3 = 9
c = 6 + 9 = 15.

c is a pointer to the y-value, so the program takes the value '15' and follows that pointer back your your initial y value and sets y = 15. So you print out 15 instead of 3.
Last edited on
Hi,

The value of x is the same because you pass the value on the funtion by value, while y pass by reference. So if you pass by value no matters what happen in the funtion the value doesnt change. But if you pass the value by reference (& c), in this case y change.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  #include <iostream>
using namespace std;
void Sum(int a, int b, int & c)
{
	
	a = b + c;   // a= 3+3 = 6
	b = a + c;  // b = 6+3 = 9
	c = a + b;  // c = 6+9 = 15 ==> here c change because was passed by reference
                                                      // and a = x = 2 because was passed by value
                                                      // and b = y = 3 because was passed by value too.
}
int main()
{
	int x = 2, y = 3;
	Sum(x, y, y);
	cout << x << " " << y;
	system("pause");
	return 0;
}
//Put the code you need help with here.  


So,
You have `a = int x , ´b = y´ these values were passed by value and ´c = y´ was passed by reference, the difference is the operator `& = reference`. that`s why the value of y change.


Sorry if my english doesn`t good, Im learning :D
you passed an argument to c WITH reference ( & ); therefore, what ever you do to c will change the original variable (which in your case y). But, now, did you pass x to a with reference, no. then why would the original x change? just add a small reference & to a and it will be okay.
got it...crystal clear...thanks to ulutay ,java 90 and militie for your valuable time and efforts..lauded..
@ java90: English is just a language, not a knowledge.feel cool...i appreciate ur programming knowledge.thanks for ur effort...
Topic archived. No new replies allowed.