|
|
|
|
|
|
|
FIGURE 5.1
When a program calls a function, execution switches to
the function and then resumes at the line after the
function call. |
|
|
|
|
|
|
|
|
A well-designed function will perform a specific task. That means it does one thing, does it well, and then returns. |
|
|
|
|
|
|
|
|
Complicated tasks should be broken down into multiple functions, and then each can be called in turn. This makes your code easier to understand and easier to maintain. |
|
|
|
|
|
|
|
|
You will find throughout this book that I talk a lot about making your program easy to maintain. The big cost in programming is not writing the program, it is keeping it useful and reliable throughout its shelf-life. |
|
|
|
|
|
|
|
|
Declaring and Defining Functions |
|
|
|
|
|
|
|
|
Before you can use a function, you must first declare the function and then define the function. |
|
|
|
|
|
|
|
|
New Term: The declaration tells the compiler the name, return type, and parameters of the function. The declaration of a function is called its prototype. |
|
|
|
|
|
|
|
|
New Term: The definition tells the compiler how the function works. No function can be called from any other function that hasn't first been declared. |
|
|
|
|
|
|
|
|
The built-in functions supplied by your compiler vendor will have their function prototypes already written. You just #include the appropriate file and you're all set. |
|
|
|
|
|
|
|
|
New Term: The function prototype is a statement, which means it ends with a semicolon. It consists of the function's return type, name, and parameter list. |
|
|
|
|
|
|
|
|
The parameter list is a list of all the parameters and their types, separated by commas. Figure 5.2 illustrates the parts of the function prototype. |
|
|
|
|
|