8.6. Pass by value

When you pass a structure as an argument, remember that the argument and the parameter are not the same variable. Instead, there are two variables (one in the caller and one in the callee) that have the same value, at least initially. For example, when we call print_point, the stack diagram in Fig. 8.2 shows:

function call stack diagram

Fig. 8.2 Function call stack diagram

If print_point happened to change one of the instance variables of p, it would have no effect on blank. Of course, there is no reason for print_point to modify its parameter, so this isolation between the two functions is appropriate.

This kind of parameter-passing is called "pass by value" because it is the value of the structure (or other type) that gets passed to the function.

Remember pass by value will always make a copy, leaving the original unchanged.

Take a look at the active code below. Notice from the output of the code below how the function add_two changes the instance variables, but not on blank itself.

Example call_by_value_AC_1
 1#include <iostream>
 2
 3struct point {
 4    double x;
 5    double y;
 6};
 7
 8 void add_two (point p) {
 9    std::cout << '(' << p.x + 2 << ", " << p.y + 2 << ")\n";
10}
11
12int main() {
13    point blank = { 3.0, 4.0 };
14    add_two (blank);
15    std::cout << '(' << blank.x << ", " << blank.y << ")\n";
16}

Q1

What will print?

int add_two(int x) {
  cout << x << ' ';
  x = x + 2;
  cout << x << ' ';
  return x;
}

int main() {
  int num = 2;
  add_two(num);
  cout << num << '\n';
}

Q2

What will print?

struct point {
  int x, y;
};

void times_two (point p) {
  p.x = p.x * 2;
  p.y = p.y * 2;
  cout << '(' << p.x << ", " << p.y << ')';
}

int main() {
  point blank = { 3, 4 };
  times_two (blank);
  cout << ", " << blank.x << '\n';
}