# Thread: Function retuning incorrect value

1. ## Function retuning incorrect value

Hi all, I'm revising for my intro to computing class short-test two, and going through a previous year paper, I attempted to solve this function on paper, and the answer I got on paper for a was 6, but when I run the program and print a, it yields a value of 3. What am I doing wrong here? Please and thank you, any feedback is welcomed.
Code:
```void foo (int x, int & y)
{
int c;
c = x + y;
y = 2 * c;
x = 2 * x;
}```

In the main program, if you have the following code:
int a = 3, b = 3;
foo(a, b);

What is the value of the variable “a” after “foo” is called (and executed) in the main program as above

What exactly am I doing wrong here?

2. Your mistake is in thinking that a is modified from within foo. Rather, the parameter x holds a copy of the value of a. The value of a itself is not changed.

3. So if x holds a copy of the value of "a", then why is the value of "y" changed? Is it due to the fact that, "y" is passed by reference? But if both values go into foo, then shouldn't both values be changed?

4. Originally Posted by cool_guy
So if x holds a copy of the value of "a", then why is the value of "y" changed? Is it due to the fact that, "y" is passed by reference?
Yes.

Originally Posted by cool_guy
But if both values go into foo, then shouldn't both values be changed?
The difference is that the reference parameter y becomes an alias for the variable b, so changes to y are reflected in b.

5. Oh, I think I understand now. IF a function is called and if the parameter is passed by reference, then any changes to the values that are passed, also affect the real variable?

6. Originally Posted by cool_guy
Oh, I think I understand now. IF a function is called and if the parameter is passed by reference, then any changes to the values that are passed, also affect the real variable?
Easy said (and if I am right) a value not passed in is assigned to a local variable and is only available inside the function.

Your variable a is a local variable inside the main function and has no meaning in your function foo. In there a new variable called a is created when you try to use it.