CS110 Lab: C++ Function with Value-parameters
A variable declared in the heading of a function is called a parameter, also called a formal argument or a formal parameter. A variable or expression included in the call to a function is referred to as an argument, also known as an actual argument or actual parameter. Please read the following for further information:
- A parameter is a value parameter if its data type does not end with an ampersand (&).
- There must be the same number of arguments in a function call as there are parameters in the heading of the function.
- Each argument should have the same data type as the parameter in the same position.
- When the function is called, a copy of the value of the argument is passed to the function. Therefore, the caller argument cannot be accessed directly or changed.
- When the function returns, the contents of its value parameters are destroyed, along with the local variables.
- The difference between value parameters and local variables is that the values of local variables are undefined when a function starts to execute, whereas value parameters are automatically initialized to the values of corresponding arguments.
Example
In the above example, the heading of printStars()
function is
void printStars(int numOfStars)
.
The parameter numOfStars
is a value
parameter because its data type int
does not end with an ampersand ( &
).
When it is called using the argument num_stars
, i.e. printStars(num_stars);
, then parameter numOfStars
receives a copy of the value of
num_stars
.
While the function runs there are two copies of the data: one in the argument
num_stars
and one in the parameter
numOfStars
. If a statement inside the
function printStars()
were to change
the value of numOfStars
, this change
would not affect the argument num_stars
.