< previous page page_24 next page >

Page 24
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
10:    // function main - prints out a message, then
11:    // calls DemonstrationFunction, then prints out
12:    // a second message.
13:    int main()
14:    {
15:        cout << In main\n ;
16:        DemonstrationFunction();
17:        cout << Back in main\n;
18:        return 0;
19:    }

Output:
In main
In Demonstration Function
Back in main
Analysis: The function DemonstrationFunction() is defined on lines 58. When it is called, it prints a message to the screen and then returns.
Line 13 is the beginning of the actual program. On line 15, main() prints out a message saying it is in main(). After printing the message, line 16 calls DemonstrationFunction(). This call causes the commands in DemonstrationFunction() to execute. In this case, the entire function consists of the code on line 7, which prints another message. When DemonstrationFunction() completes (line 8), it returns to where it was called from. In this case, the program returns to line 17, where main() prints its final line.
Using Functions.
Functions either return a value, or they return void, meaning they return nothing. A function that adds two integers might return the sum, and thus would be defined as returning an integer value. A function that just prints a message has nothing to return and would be declared to return void.
Functions consist of a header and a body. The header consists, in turn, of the return type, the function name, and the parameters to that function. The parameters to a function allow values to be passed into the function. Thus, if the function were to add two numbers, the numbers would be the parameters to the function. Here's a typical function header:
int Sum(int a, int b)
A parameter is a declaration of what type of value will be passed in; the actual value passed in by the calling function is called the argument. Many programmers use these

 
< previous page page_24 next page >

If you like this book, buy it!