Call-by-Value Parameters

  1. The parameters of the class of functions we are considering in this chapter are referred to as call-by-value parameters.

  2. When a function is called, its parameters must have values. These parameters are referred to as the actual parameters because their values are actually used by the function to calculate the returned value of the function.

    • When the function is called, the values of the actual parameters are copied to the corresponding formal parameters of the function.

    • The value of the first actual parameter is copied to the first formal parameter, the value of the second actual parameter is copied to the second formal parameter, etc.

    • The process in which the formal parameters of the function are initialized using the values of the corresponding actual parameters during a function call is referred to as call-by-value.

    • Program control is then passed to the function and the statements within the function body are executed until a return statement is encountered.

    • Then the expression of the return statement is evaluated and its value is considered as the value of the function.

    • The function stops executing and that value is then returned to the calling function.

    • Program control is also passed back to the calling function where the function call took place.

    • Program execution then continues from there.

  3. Before a function call is made, a function's local variables and its formal parameters have no meaningful values.

  4. After returning to its calling function, a function's local variables and formal parameters are no longer accessible.

  5. Practically the only way that information can be passed from the calling function to the function that is called is through the actual parameters. Avoid using global variables!

  6. Practically the only way that information can be passed from the function back to the calling function is through the return value of the function.

  7. Therefore at most one piece of information can be passed back to the calling function.

  8. Advantage for using value arguments in a function -- value arguments offer some protection to data integrity. Because copies of value arguments are stored locally in the called function's data area, the actual argument's value is protected from being erroneously changed by the function's execution.

  9. Disadvantages for using value arguments in a function --

    • At most one piece of information can be passed back to the calling function.

    • The process of copying the value of a value argument to the memory location of the corresponding formal parameter can be rather slow, especially when a lot of data have to be copied this way.