Sams Teach Yourself C++ in 21 Days

(singke) #1
The Anatomy of a C++ Program 35

2


Functions................................................................................................................


Althoughmain()is a function, it is an unusual one. To be useful, a function must be
called, or invoked, during the course of your program. main()is invoked by the operat-
ing system.
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 point 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.6 demonstrates this idea.

Functions are covered in more detail on Day 5, “Organizing into Functions.”
The types that can be returned from a function are covered in more detail
on Day 3, “Working with Variables and Constants.” The information pro-
vided today is to present you with an overview because functions will be
used in almost all of your C++ programs.

NOTE


LISTING2.6 Demonstrating a Call to a Function


1: #include <iostream>
2:
3: // function Demonstration Function
4: // prints out a useful message
5: void DemonstrationFunction()
6: {
7: std::cout << “In Demonstration Function\n”;
8: }
9:
10: // function main - prints out a message, then
11: // calls DemonstrationFunction, then prints out
12: // a second message.
13: int main()
14: {
15: std::cout << “In main\n” ;
16: DemonstrationFunction();
17: std::cout << “Back in main\n”;
18: return 0;
19: }
Free download pdf