When pass a variable to a function, why the function only gets a duplicate of the variable?

The are basically two schools of thought on this matter.

The first is pass-by-value where a copy of the value is created for the called function.

The second is pass-by-reference where the parameter that appears in the called function is an “alias” of the original. That means changes you make to it are reflected in the original.

C is generally a pass-by-value language. You can emulate pass-by-reference by passing the address of a variable and then using that to modify the original:

void setTo42 (int *x) { *x = 42; }
:
int y;
setTo42 (&y);
// y is now 42

but that’s more passing the pointer to a variable by value, than passing the variable itself by reference.

C++ has true reference types, possibly because so many people have trouble with C pointers 🙂 They’re done as follows:

void setTo42 (int &x) { x = 42; }

:
int y;
setTo42 (y);
// y is now 42

Pass-by-value is usually preferable since it limits the effects that a function can have on the “outside world” – encapsulation, modularity and localisation of effect is usually a good thing.

Being able to arbitrarily modify any parameters passed in would be nearly as bad as global variables in terms on modularity and code management.

However, sometimes you need pass-by-reference since it might make sense to change one of the variables passed in.

Leave a Comment