Professional Documents
Culture Documents
C++ Functions: Variable Scope Storage Class Recursion
C++ Functions: Variable Scope Storage Class Recursion
Variable Scope
Storage Class
Recursion
n ame parameters
ct ion
Fu n
#include <math.h>
fabs fmod
C++ Spring 2000 Functions 10
Writing a function
• You have decide on what the function will
look like:
– Return type
– Name
– Types of parameters (number of parameters)
• You have to write the body (the actual
code).
return(sum);
}
C++ Spring 2000 Functions 13
Testing add2nums
int main(void) {
int y,a,b;
y = add2nums(a,b);
i st
{ t ex
’
n k!
int a = y; s
e oc
o
d bl
a e
cout << a << endl; r th –
r ro ide
} E ts
ou
cout << a << endl;
}
C++ Spring 2000 Functions 21
Nesting
• In C++:
– There is no nesting of function definitions.
• You don’t need to know who calls a function to
know the scope of it’s variables!
int counter(void);
int main(void) {
cout << counter() << endl;
cout << counter() << endl;
cout << counter() << endl;
}
int counter(void) {
static int count = 0;
count++;
return(count);
}
foo1 foo2
… …
foo2() foo1()
… …
int main(void) {
int startnum;
Recursive Step:
n area = n+n-1+area(n-1)
triangle(4); triangle(5);
* *
*** ***
***** *****
******* *******
*********
int &foo;
double &blah;
char &c;
count = 1;
cout << “blah is “ << blah << endl;
blah++;
cout << “count is “ << count << endl;
n ce
void add10( int &x) { efe re
is ar
x = x+10; e ter
r a m
} pa
The
…
add10(counter);