What is scope?

The scope of a variable is the region of space where the value of that variable is valid.

The main reason for a scope is to keep variables with the same names confined to separate parts of a program. Programmers may use the same variable names repeatedly; therefore, the scope defines the region in which that variable is valid.

widget

There are two types of scope:

  1. Global Scope
  2. Local Scope

They are both described in detail below.

1. Global Scope

Variables defined in the global scope can be accessed anywhere throughout the program. They are available to all the functions across the program.

Remember: global variables are available from the point they are defined until the end of the scope. This is a major reason why most global variables are declared at the start, to ensure their availability across the program.

#include <iostream>
using namespace std;
string name = "Alex"; // declare a global variable
int main() {
name= "Bob"; // update the value of variable in function
cout << name << endl; //print variable
return 0;
}

2. Local Scope

Variables defined in the local scope are only available inside the functions, loops, or classes in which they are defined.

Remember: global variables can exist with the same name; however, the compiler will always consider the variables within the local scope first. This means that global variables will not be called if a similar local variable exists.

This is shown below.

#include <iostream>
using namespace std;
//declare a global variable x
int x = 100;
int main() {
//declare a local variable x
int x = 10;
//update the value of x
x += 10;
//print value of x
cout << x << endl;
return 0;
}

The above example suggests that if a global variable needs to be updated, it should be ensured that no local variable with the same name exists or that the scope resolution operator is used.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved