Passing by value vs reference

So I understand the purpose of each, but do you ever HAVE to pass by reference? Let's say you have

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int x = 12;
int y = 24;

testFunc(x,y);
...
...

//Takes the values of x and y
void testFunc(int a, int b)
{
    a = x;
    b = y;
    //Perform some changes to a and b here...

    x = a;
    y = b;
    //Would this not do the same thing as passing these values by reference?
}
That only works because you are using global variables (not recommended). It is not really the same as passing by reference, although in this example it happens to have the same effect.

The point is that the function should not know or care what the name of the variables are on the outside. Using a reference gets the compiler to manage the identifier switcheroo.
Of course yes, when you need an argument to be modified in the caller's context after the function call.
Ah thanks Galik, that makes sense when you think about a more large scale program.
Passing by value copies the value itself, while passing by reference basically copies a memory address.

You normally pass by const reference to conserve memory... which is manual optimization... which should not be your concern in a high-level language... but whatever.

Another case is what wjee0910 posted.
Topic archived. No new replies allowed.