Functions in C++

While main() is a function, it is an unusual one. Typical functions are called, or invoked, during the course of your program. A program is executed line by line in the order it appears in your source code, until a function is reached. Then the program branches off to execute the function. When the function finishes, it returns control to the line of code immediately following the call to the function.

A good analogy for this is sharpening your pencil. If you are drawing a picture, and your pencil breaks, you might stop drawing, go sharpen the pencil, and then return to what you were doing. When a program needs a service performed, it can call a function to perform the service and then pick up where it left off when the function is finished running. Listing 2.4 demonstrates this idea.

Listing 2.4. Demonstrating a call to a function.
1:     #include <iostream.h>
3:     // function Demonstration Function
4:     // prints out a useful message
5:     void DemonstrationFunction()
6:     {
7:         cout << "In Demonstration Function\n";
8:     }
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: }
In main
In Demonstration Function
Back in main
The function DemonstrationFunction() is defined on lines 5-7. 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 back to where it was called from. In this case the program returns to line 17, where main() prints its final line. 

Functions in C++ Reviewed by 1000sourcecodes on 08:51 Rating: 5
Powered by Blogger.