Functions with Parameters
Tom Kelliher, CS17
Mar. 25, 1996
int add(int a, int b);
int main()
{
int i = 12;
int j = 4;
int k;
k = add(i, j);
cout << k << endl;
return 0;
}
int add(int a, int b)
{
return a + b;
}
- Calling, called function.
- Calling functions communicates through parameters.
- Called function communicates through return value.
- Don't use global variables for communication.
Consider:
void f(void);
void changeMe(int);
void f(void)
{
int a = 5;
int i = 2;
changeMe(4);
changeMe(a);
cout << a << endl;
changeMe(i);
cout << i << endl;
changeMe(i + 4);
}
void changeMe(int a)
{
a = 0;
}
Is changeMe(4); legal?
What's printed?
- A Formal parameter:
- Function declaration, definition.
- Always a variable.
- Local variable of function.
- Local scope, visibility.
- An Actual parameters
- Function call.
- Any expression of appropriate type.
- Must match in lists.
Semantics of a function call:
- Storage allocated for the formal parameters.
- Actual arguments evaluated within calling function.
- Their values used to initialize formal parameters.
- Called function runs.
- Storage for formal parameters de-allocated when called function
returns.
-
Design a modular program which computes factorials of non-negative integers:
The program should
accept positive integers from the user, asking them if they want to
continue, and output the factorial of the input.
-
Using modules from the previous program, write a modular program which
computes combinations. The formula is:
C(n,r) is the number of ways in which r objects can be
drawn from a set of n objects, assuming that order doesn't matter.
The user interface of this program should be similar to the previous one.
I.e., accept input for several computations, ask the user if they want to
continue, etc.
Thomas P. Kelliher
Thu Mar 21 13:29:29 EST 1996
Tom Kelliher