Variable Scope

Learn about the local and global variable scopes in C++.

In this lesson, we will learn about the concept known as the variable scope.

Variable scope

In C++, variables are only accessible within their boundaries which is called the scope of a variable. It is very important to know the scope of a variable since a variable can not be accessed outside of its boundaries. The variable, in terms of their scope, has two types:

  • Local variable
  • Global variable

Local variable

A local variable is only accessible within the curly brackets { } where it is declared.

The lines of code inside the curly braces are referred to as a block of code.

Let’s run the code below to understand what we mean.

Press + to interact
// Local variable scope
#include <iostream>
using namespace std;
int main()
{
int a = 100;
{
int b = 200;
}
cout << a << endl;
cout << b << endl;
return 0;
}

Did you see an error? Don’t worry if you do! We wanted you to see this error. Can you guess why it occurred?

In the code above, there are two integer variables a and b declared on lines 8 and 10. Variable a is declared in the main scope so we can access it in the whole of main, after its declaration, i.e., line 8. Variable b, on the other hand, is inside the curly brackets which is the scope of the variable b. We get an error on line 13 because we are trying to print b outside of its scope. During execution, whenever we enter a scope, the variables are created and allocated appropriate memories, and as soon as the execution leaves the block, all the memory variables allocated inside that block are erased from the memory.

As variable b is not accessible outside its scope (within curly brackets on lines 9 and 10), we can only access variable b inside its scope.

Click “Run” in the code editor below to run the code (using a debugger this time!) line by line to inspect the life of the variables (especially variable b).

Upon running the code step-by-step (on the right-side panel under local variables), we’ll see the variables a and b. We’ll see that b is only available within the inner block (lines 9–12) and is destroyed as soon as it goes out of scope.

Observe the following: As soon as the execution enters the block, the memory for all the variables within that block is created (with garbage values inside, and the moment the initialization line gets executed, the garbage value gets replaced by the initialized value.

// Local variable scope
#include <iostream>
using namespace std;


int main()
{
    int a = 100;
    {
        int b = 200;
        cout << b << endl;
    }
    cout << a << endl;
    return 0;
}

Scope of local variable 'b'

Also, now upon running the code above, we don’t get any errors. This is because now we’re accessing b inside its scope (within the curly brackets where it is declared).

Global variable

Global variables are those variables that are accessible in the whole program. Global variables must be declared outside the int main(). You can initialize global variables anywhere in the program.

A global variable is automatically initialized with the default value (if it is not already initialized). The table below shows what default value each data type is initialized with:

Default Values of Global Variables

Data Type

Initialized with Value

int

0

char

‘\0’ (Null Character)

float

0.0

double

0.0

Local variables, unlike global variables, are not automatically initialized. We have to initialize the local variable. Otherwise it stores a garbage value (any random number given by the computer).

Now let’s see an example of a global variable. Below is the code editor, click “Run” to execute.

Press + to interact
#include <iostream>
using namespace std;
// global variable scope
int a;
int main()
{
cout << a << endl;
a = 100;
cout << a << endl;
return 0;
}

In the above example, global variable a is declared outside the int main() at line 5. At line 8 we then simply display the value of the variable a, which is automatically initialized with 0 since we did not initialize it at line 5. At line 9 we initialize variable a with 100 and then we display that variable again but this time the output is 100.

To understand the global and local scopes better, look at the code below. Before clicking the “Run” button to see the output, guess the possible output of each cout statement.

The operator :: is called a scope resolution operator. It can be used to refer to the global variable when both the local and global variable names are the same.

Again, run the code step-by-step to see the output.

// global variable scope

#include <iostream>
using namespace std;

int a = 100;
int main()
{
    cout << a << endl; // this will print 100
    int a = 200;
    cout << a << endl; // this will print 200
    {
        cout << a << endl; // this will print 200
        int a = 300;
        cout << a << endl; // this will print 300
        cout << ::a << endl; // this will print 100
    } // the variable 'a' inside the block will be destroyed

    cout << a <<endl; // this should print 200
    cout << ::a<<endl; // this should print 100
    return 0;
}

Accessing global and local variables

In the code above, the variable a initialized with 100 in line 6 is a global variable. Its value is accessed in lines 16 and 20 using the scope resolution operator.

One important point to note is that whatever local variable is created within some block (for example, variable a from lines 12 to 17), it can not be accessed outside of its scope. The local variable within that scope is destroyed as soon as the control leaves the scope. In short, the variable a which is assigned the value 300 gets destroyed after line 17.

That’s why in line 19, 200 is printed and not 300.