Sams Teach Yourself C++ in 21 Days

(singke) #1

What Is a Function? ............................................................................................


A function is, in effect, a subprogram that can act on data and return a value. Every C++
program has at least one function,main(). When your program starts, the main()func-
tion is called automatically. main()might call other functions, some of which might call
still others.
Because these functions are not part of an object, they are called “global”—that is, they
can be accessed from anywhere in your program. For today, you will learn about global
functions unless it is otherwise noted.
Each function has its own name, and when that name is encountered, the execution of the
program branches to the body of that function. This is referred to as callingthe function.
When the function finishes (through encountering a returnstatement or the final brace
of the function), execution resumes on the next line of the calling function. This flow is
illustrated in Figure 5.1.

100 Day 5


FIGURE5.1
When a program calls
a function, execution
switches to the func-
tion and then resumes
at the line after the
function call.

Program
Main ()
Statement;
func1 ();
Statement
func2 ();
Statement;
func4 ();
Statement;

func1

return

func4

return;

func3

return;

func2
Statement
func3 ();
return;

{

}

Well-designed functions perform a single, specific, and easily understood task, identified
by the function name. Complicated tasks should be broken down into multiple functions,
and then each can be called in turn.
Functions come in two varieties: user-defined and built-in. Built-in functions are part of
your compiler package—they are supplied by the manufacturer for your use. User-
defined functions are the functions you write yourself.

Return Values, Parameters, and Arguments ........................................................


As you learned on Day 2, “The Anatomy of a C++ Program,” functions can receive val-
ues and can returna value.
Free download pdf