Call by value

suggest change

Upon calling a function there are new elements created on the program stack. These include some information about the function and also space (memory locations) for the parameters and the return value.

When handing over a parameter to a function, the value of the used variable (or literal) is copied into the memory location of the function parameter. This implies that there are now two memory locations with the same value. Inside the function we only work on the parameter’s memory location.

After leaving the function, the memory on the program stack is popped (removed), which erases all data of the function call, including the parameters. Thus, the values changed inside the function do not affect the outside variables’ values.

int func(int f, int b) { 
  //new variables are created and values from the outside copied
  //f has a value of 0
  //inner_b has a value of 1
  f = 1;
  //f has a value of 1
  b = 2;
  //inner_b has a value of 2
  return f+b;
}

int main(void) {
  int a = 0;
  int b = 1; //outer_b
  int c;

  c = func(a,b);
  //the return value is copied to c
  
  //a has a value of 0
  //outer_b has a value of 1   <--- outer_b and inner_b are different variables
  //c has a value of 3
}

In this code we create variables inside main and assign values to them. The call creates two parameters, f and b. That parameter b shares its name with the variable in main, but not its memory. The behavior of a and f, and of the two variables named b, is the same: each parameter is a copy.

The following graphic symbolizes what is happening on the stack and why there is no change in variable b. The graphic is not fully accurate but emphasizes the example.

It is called “call by value” because we do not hand over the variables but only the values of these variables.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents