Free Hosting

Function parameters and arguments


You should be familiar with the concepts discussed in those lessons before proceeding.
Parameters vs Arguments
Up until now, we have not differentiated between function parameters and arguments. In common usage, the terms parameter and argument are often interchanged. However, for the purposes of further discussion, we will make a distinction between the two:
function parameter is a variable declared in the prototype or declaration of a function:
1
2
3
4
5
void foo(int x); // prototype -- x is a parameter
 
void foo(int x) // declaration -- x is a parameter
{
}
An argument is the value that is passed to the function in place of a parameter:
1
2
foo(6); // 6 is the argument passed to parameter x
foo(y+1); // the value of y+1 is the argument passed to parameter x
When a function is called, all of the parameters of the function are created as variables, and the value of the arguments are copied into the parameters. For example:
1
2
3
4
5
void foo(int x, int y)
{
}
 
foo(6, 7);
When foo() is called with arguments 6 and 7, foo’s parameter x is created and assigned the value of 6, and foo’s parameter y is created and assigned the value of 7.
Even though parameters are not declared inside the function block, function parameters have local scope. This means that they are created when the function is invoked, and are destroyed when the function block terminates:
1
2
3
void foo(int x, int y) // x and y are created here
{
} // x and y are destroyed here
There are 3 primary methods of passing arguments to functions: pass by value, pass by reference, and pass by address. The following sections will address each of those cases individually.

0 comments:

Blogger Template by Clairvo