Chapter 9: Functions


Overview

A function is a group of statements that together perform a task. So far, our programs have had one function, main. Additionally, at times we have used functions defined in a standard library, such as the pow function in the cmath library, used to raise a number to a certain power.

No program needs more than a main function. However, as you write more complex and sophisticated programs, you may find your main function becoming extremely long.

Neither the compiler nor the runtime cares if your main function is short or long. However, you should care. A main function that continues for pages is difficult to understand or fix if errors arise.

By analogy, this book is several hundred pages long. It would be harder to understand if each chapter was not divided into sections. This book would be still harder to understand if it consisted of only one, very long chapter. By dividing this book s content into chapters, and each chapter into sections, this book is easier to understand.

Similarly, you can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division usually is so each function performs a specific task.

For example, in a program that performs arithmetic calculations, one function obtains user input, another function performs the calculation, and a third function performs output of the result. This is analogous to how a book is divided up into chapters and sections. Each chapter explores a different subject. One chapter focuses on variables , another (this one) on functions.

There are advantages to dividing your code into separate functions in addition to making your code easier to understand. For example, if a function performs a specific task, such as sending output to a printer, which is performed several times in a program, you only need to write once in a function the code necessary to send output to the printer, and then call that function each time you need to perform that task. Otherwise, the code necessary to send output to the printer would have to be repeated each time that task was to be performed.

Hopefully, I have persuaded you that organizing your code into separate functions can be useful. I will now show you how to do it.




C++ Demystified(c) A Self-Teaching Guide
C++ Demystified(c) A Self-Teaching Guide
ISBN: 72253703
EAN: N/A
Year: 2006
Pages: 148

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net