6.2.1. Passing Arguments by Value

Image

When we initialize a nonreference type variable, the value of the initializer is copied. Changes made to the variable have no effect on the initializer:

int n = 0;             // ordinary variable of type int
int i = n;             // i is a copy of the value in n
i = 42;                // value in i is changed; n is unchanged

Passing an argument by value works exactly the same way; nothing the function does to the parameter can affect the argument. For example, inside fact6.1, p. 202) the parameter val is decremented:

ret *= val--;  // decrements the value of val

Although fact changes the value of val, that change has no effect on the argument passed to fact. Calling fact(i) does not change the value of i.

Pointer Parameters

Pointers (§ 2.3.2, p. 52) behave like any other nonreference type. When we copy a pointer, the value of the pointer is copied. After the copy, the two pointers are distinct. However, a pointer also gives us indirect access to the object to which that pointer points. We can change the value of that object by assigning through the pointer (§ 2.3.2, p. 55):

int n = 0, i = 42;
int *p = &n, *q = &i; // p points to n; q points to i
*p = 42;              // value in n is changed; p is unchanged
p = q;                // p now points to i; values in i and n are unchanged

The same behavior applies to pointer parameters:

// function that takes a pointer and sets the pointed-to value to zero
void reset(int *ip)
{
    *ip = 0;  // changes the value of the object to which ip points
    ip = 0;   // changes only the local copy of ip; the argument is unchanged
}

After a call to reset, the object to which the argument points will be 0, but the pointer argument itself is unchanged:

int i = 42;
reset(&i);                    // changes i but not the address of i
cout << "i = " << i << endl;  // prints i = 0


Image Best Practices

Programmers accustomed to programming in C often use pointer parameters to access objects outside a function. In C++, programmers generally use reference parameters instead.



Exercises Section 6.2.1

Exercise 6.10: Using pointers, write a function to swap the values of two ints. Test the function by calling it and printing the swapped values.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.154.64