Node:Actual parameters and formal parameters, Next:Variadic functions, Previous:Value parameters, Up:Parameters
Actual parameters and formal parameters
There are two other categories that you should know about that are also referred to as "parameters". They are called "parameters" because they define information that is passed to a function.
- Actual parameters are parameters as they appear in function calls.
- Formal parameters are parameters as they appear in function declarations.
A parameter cannot be both a formal and an actual parameter, but both formal parameters and actual parameters can be either value parameters or variable parameters.
Let's look at calculate_bill
again:
#include <stdio.h> int main (void); int calculate_bill (int, int, int); int main() { int bill; int fred = 25; int frank = 32; int franny = 27; bill = calculate_bill (fred, frank, franny); printf("The total bill comes to $%d.00.\n", bill); exit (0); } int calculate_bill (int diner1, int diner2, int diner3) { int total; total = diner1 + diner2 + diner3; return total; }
In the function main
in the example above, fred
,
frank
, and franny
are all actual parameters when used to
call calculate_bill
. On the other hand, the corresponding
variables in calculate_bill
(namely diner1
, diner2
and diner3
, respectively) are all formal parameters because they
appear in a function definition.
Although formal parameters are always variables (which does not mean
that they are always variable parameters), actual parameters do not have
to be variables. You can use numbers, expressions, or even function
calls as actual parameters. Here are some examples of valid actual
parameters in the function call to calculate_bill
:
bill = calculate_bill (25, 32, 27); bill = calculate_bill (50+60, 25*2, 100-75); bill = calculate_bill (fred, franny, (int) sqrt(25));
(The last example requires the inclusion of the math routines in
math.h
, and compilation with the -lm
option.
sqrt
is the square-root function and returns a double
, so
it must be cast into an int
to be passed to
calculate_bill
.)