Chapter 9. Variable Scope and Functions

But in the gross and scope of my opinion, This bodes some strange eruption to our state.

—Shakespeare, Hamlet, Act I, Scene I

So far you have been using only global variables. These are variables that can be set or used almost anywhere in the program. In this chapter you learn about other kinds of variables and how to use them. This chapter also tells you how to divide your code into functions. Many aspects of functions are detailed, including function overloading, using functions to build structured programs, and the use of recursive function calls.

Scope and Storage Class

All variables have two attributes, scope and storage class. The scope of a variable is the area of the program where the variable is valid. A global variable is valid from the point it is declared to the end of the program. A local variable’s scope is limited to the block where it is declared and cannot be accessed (set or read) outside that block. A block is a section of code enclosed in curly braces ({ }). Figure 9-1 illustrates the difference between local and global variables.

Local and global variables

Figure 9-1. Local and global variables

It is possible to declare a local variable with the same name as a global variable. Normally, the scope of the variable count (first declaration in Figure 9-2) would be the whole program. The declaration of a second, local count takes precedence over ...

Get Practical C++ Programming, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.