Skip to Main Content
Practical C++ Programming, 2nd Edition
book

Practical C++ Programming, 2nd Edition

by Steve Oualline
December 2002
Beginner to intermediate content levelBeginner to intermediate
576 pages
14h 6m
English
O'Reilly Media, Inc.
Content preview from Practical C++ Programming, 2nd Edition

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 the global ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Discovering Modern C++, 2nd Edition

Discovering Modern C++, 2nd Edition

Peter Gottschling

Publisher Resources

ISBN: 0596004192Supplemental ContentErrata Page