Download CD Content
In this chapter, you will learn how to:
Declare function prototypes
Define function bodies
Deal with local and global variable scope
Define and use overloaded functions
By now, you should be fairly comfortable with basic C++ syntax. You’ve seen how to declare variables, write statements, use operators, and perform simple console output. However, as your programs start to get larger, you need to organize your code to cope with the growing complexity.
In this chapter, you will learn how to divide a Microsoft Visual C++ program into functions. First you’ll see how to declare function prototypes to introduce the functions to the compiler. Next you’ll see how to define function bodies to carry out the required processing. For example, you might write a function to calculate the expected growth on an investment or to get the user’s password from a Logon screen. Finally you’ll see how to call a function from elsewhere in your program.
There are many good reasons for dividing a program into functions:
Each function is usually quite short and discrete. It’s easier to write a program as a series of functions than as a single long one, because you can concentrate on one function at a time.
It’s also easier to read and debug a program that contains lots of small functions than one that contains a single long one, because you don’t have to remember what the whole program is doing.
Functions are reusable. Once you’ve written a function, you can call it whenever you need it in your program, which reduces coding effort, and therefore improves developer productivity.