Nothing Special   »   [go: up one dir, main page]

Open In App

Scope of Variables in C++

Last Updated : 10 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

In C++, the scope of a variable is the extent in the code upto which the variable can be accessed or worked with. It is the region of the program where the variable is accessible using the name it was declared with.

Let’s take a look at an example:

C++
#include <iostream>
using namespace std;

// Declaring first variable
int a = 10;

int main() {

      // Declaring second variable
      int b = 9;

      // Accessing a and b variable in their scope
    cout << a << " " << b;

    return 0;
}

Output
10 9

Explanation: The variables a and b are declared in some part of the program and accessed in other part. It is possible because the accessing is done in the scope where the variables are valid.

You may have noticed that though variable b is declared inside the main function, variable a is declared outside any function, but we can still access both of them in the main function. You may wonder, can we access b outside main function? The answer is NO. It is due to the difference in the scope of two variables.

In C++, there are mainly two types of variable scopes:

Table of Content

Now let’s understand each of the scope in a greater detail.

Global Scope

Global scope refers to the region outside any function or a block. The variables declared here are accessible throughout the entire program and are called Global Variables.

Let’s take a look at an example:

C++
#include<iostream>
using namespace std;

// Global variable
int global = 5;

// Global variable accessed from within
// a function
void display() {
    cout << global << endl;
}

int main() {
    display();
    
    // Changing value of global from main
      // function before calling display()
    global = 10;
    display();
  
      return 0;
}

Output
5
10

Explanation: In the program, the variable “global” is declared at the top of the program outside all of the functions so it is a global variable and can be accessed or updated from anywhere in the program.  

Local Scope

The local scope is the region inside the curly braces { }. Variables defined within a function or block are said to be local to those functions or a block and are called local variables. Local variables do not exist outside the block in which they are declared, i.e. they cannot be accessed or used outside that block.

Let’s take a look at an example:

C++
#include<iostream>
using namespace std;

void func() {
  
    // This variable is local to function func() and
      // cannot be accessed outside this function
    int age = 18;
}

int main() {
  
      // Accessing variable from func() in main function
    cout << "Age is: " << age;
    
    return 0;
}


Output

./Solution.cpp: In function 'int main()':
./Solution.cpp:14:27: error: 'age' was not declared in this scope
     cout << "Age is: " << age;
                           ^

Explanation: The above program displays an error saying, “age was not declared in this scope“. It is because the age was declared inside the func()‘s scope so it is only accessible in that region, not in main() function.

To correct the above error, we have to display the value of variable age from the function func() only. This is shown in the below program: 

C++
#include<iostream>
using namespace std;

void func() {

    // This variable is local to function func() and
      // cannot be accessed outside this function
    int age = 18;
    cout << age;
}

int main() {
    cout << "Age is: ";
    func();
    
    return 0;
}

Output
Age is: 18

Variable Shadowing

Consider that there is a local variable inside a function with the same name as that of a global variable. If the function tries to access the variable with that name, then which variable will be given precedence? Look at the below program to understand the question:  

C++
#include<iostream>
using namespace std;

// Global variable
int a = 5;

int main() {
  
    // Local variable with same name as that of
      // global variable
    int a = 100;
  
      // Accessing a
    cout << a;
  
      return 0;
}

Output
100

Explanation: The variable a declared at the top is global variable and stores the value 5 whereas a declared within main function is local and stores a value 100. When accessed inside the main function, the local a’s value is printed. Also, there is no compilation error. It implies that

  • If two variables with same name are defined in different scopes, the compiler allows it and does not show error.
  • Whenever there is a local variable defined with same name as that of a global variable, the precedence is given to the local variable. This is called variable shadowing.

Access Global Variable in Variable Shadowing

The global a is still available in the main function but is shadowed by the local a as it is available everywhere. One may ask if there is any way we can access the global a in the main function.

Yes, C++ allows the users to access global variable with the same name as local variable using scope resolution operator. The below examples show how it is done:

C++
#include<iostream>
using namespace std;

// Global variable
int a = 5;

int main() {
  
    // Local variable with same name as that of
      // global variable
    int a = 100;
  
      // Accessing global a
    cout << ::a;
  
      return 0;
}

Output
5

Variations of Scopes in C++

Apart from the primary classification of the scopes as global and local, there are few other specialized variations of these scopes that divides the declared variable based on its accessibility and visibility. Following are some common variations of variable scopes in C++.

  • Instance Scope
  • Static Member Scope
  • Namespace Scope

Instance Scope

In C++, instance scope refers to the region inside a class but outside any member function of the class. The variable declared here are called instance variables and are accessible to whole class. They can be accessed by the objects of the class.

Let’s look at an example:

C++
#include <iostream>
using namespace std;

class A {
public:
  
      // Instance variable with instance scope i.e. accessible
      // in whole class
    int instanceVar;

    A(int val) {
        instanceVar = val;
    }

    void display() {
        cout << instanceVar << endl;
    }
};

int main() {
  
      // Creates a1 with instanceVar = 10
    A a1(1);
    a1.display();

      // Creates a2 with instanceVar = 20
    A a2(33);
    a2.display();

    return 0;
}

Output
1
33

Static Member Scope

The static scope applies to variables and functions declared with the static keyword within the class. These variables are shared across all instances of a class and can be accessed using the class name without creating the instance.

Let’s take a look at an example:

C++
#include <iostream>
using namespace std;

class A {
public:
  
      // Static variable with static scope i.e. accessible
      // in whole class
    static int staticVar;
};

int A::staticVar = 1;

int main() {
  
      // Access static variable
      cout << A::staticVar;

    return 0;
}

Output
1

Namespace Scope

A namespace in C++ is a container that allows users to create a separate scope where the given variables are defined. It is used to avoid name conflicts and group related code together. These variables can be then accessed using their namespace name and scope resolution operator.

For example, the below program creates a variable inside a namespace and access it later using namespace name and scope resolution operator.

C++
#include <iostream>
using namespace std;

namespace N {
      
      // Variable with namespace scope
    int namespaceVar = 10;
}

int main() {
  
      // Access variable using namespace
    cout << N::namespaceVar;  

    return 0;
}

Output
10


Next Article
Practice Tags :

Similar Reads

three90RightbarBannerImg