|
|
|
|
|
|
|
two terms, parameters and arguments as synonyms; others are careful about the technical distinction. This book will use the terms interchangeably. |
|
|
|
|
|
|
|
|
New Term: The name of the function and its parameters (that is the header without the return value) is called the function's signature. |
|
|
|
|
|
|
|
|
The body of a function consists of an opening brace, zero or more statements, and a closing brace. The statements constitute the work of the function. A function may return a value using a return statement. This statement will also cause the function to exit. If you don't put a return statement into your function, it will automatically return void at the end of the function. The value returned must be of the type declared in the function header. |
|
|
|
|
|
|
|
|
Listing 2.4 demonstrates a function that takes two integer parameters and returns an integer value. Don't worry about the syntax or the specifics of how to work with integer values (for example int x) for now. That will be covered soon. |
|
|
|
|
|
|
|
|
LISTING 2.4FUNC.CPP DEMONSTRATES A SIMPLE FUNCTION |
|
|
|
 |
|
|
|
|
1: #include <iostream.h>
2: int Add (int x, int y)
3: {
4:
5: cout << In Add(), received << x << and << y << \n;
6: return (x+y);
7: }
8:
9: int main()
10: {
11: cout << I'm in main()!\n;
12: int a, b, c;
13: cout << Enter two numbers: ;
14: cin >> a;
15: cin >> b;
16: cout << \nCalling Add()\n;
17: c=Add(a,b);
18: cout << \nBack in main().\n;
19: cout << c was set to << c;
20: cout << \nExiting\n\n;
21: return 0;
22: } |
|
|
|
|
|
|
|
|
I'm in main()!
Enter two numbers: 3 5 |
|
|
|
|
|
|
|
|
In Add(), received 3 and 5 |
|
|
|
|
|