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 fact
(§ 6.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
.
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
3.148.113.229