< Previous | Contents | Next >

Working with Separate Scopes

Every time you use curly braces to create a block, you create a scope. Functions are one example of this. Variables declared in a scope arent visible outside of that scope. This means that variables declared in a function arent visible outside of that function.

Variables declared inside a function are considered local variablestheyre local to the function. This is what makes functions encapsulated.

Youve seen many local variables in action already. I define yet another local variable in main() with:

int var = 5; // local variable in main()

This line declares and initializes a local variable named var. I send the variable to cout in the next line of code:

cout << "In main() var is: " << var << "\n\n";

164 Chapter 5 n Functions: Mad Lib


This works just as youd expect5 is displayed.

Next I call func(). Once I enter the function, Im in a separate scope outside of the scope defined by main(). As a result, I cant access the variable var that I defined in main(). This means that when I next define a variable named var in func() with the following line, this new variable is completely separate from the variable named var in main().

int var = -5; // local variable in func()

The two have no effect on each other, and thats the beauty of scopes. When you write a function, you dont have to worry if another function uses the same variable names.

Then, when I display the value of var in func() with the following line, the computer displays 5.

cout << "In func() var is: " << var << "\n\n";

Thats because, as far as the computer can see in this scope, theres only one variable named varthe local variable I declared in this function.

Once a scope ends, all of the variables declared in that scope cease to exist. Theyre said to go out of scope. So next, when func() ends, its scope ends. This means all of the variables declared in func() are destroyed. As a result, the var I declared in func() with a value of 5 is destroyed.

After func() ends, control returns to main() and picks up right where it left off. Next, the following line is executed, which sends var to cout.

cout << "Back in main() var is: " << var << "\n\n";

The value of the var local to main() (5) is displayed again.

You might be wondering what happened to the var I created in main() while I was in func(). Well, the variable wasnt destroyed because main() hadnt yet ended. (Program control simply took a small detour to func().) When a program momentarily exits one function to enter another, the computer saves its place in the first function, keeping safe the values of all of its local variables, which are reinstated when control returns to the first function.


Hi n t

image

Parameters act just like local variables in functions.

image

Working with Scopes 165