×

C++ Scope of Variables

In this tutorial, we will explore about the scope of variables in c++ programming language. And also, how it works in a program.

What is Scope?

The range of applications for something is generally referred to as its scope. The scope of a variable, as it relates to programming, is the area of the computer code that allows for access to, declaration of, and manipulation of the variable.

This implies that the name of a program element, such as a class, function, or variable, that is declared can only be "seen" and utilised in specific places inside our program. The term "scope" refers to the environment in which a name is visible. For instance, if a variable named m1 is declared inside a function, only that function body can see it. Its scope is local. Other variables with the same name may exist in our application, provided that they are in distinct scopes and do not violate the one definition rule. In this case, an error is not generated.

Scope also controls the creation and destruction of automatic non-static variables in program memory.

The rules that determine where a specific piece of code or piece of data would be known and accessible in a program are known as the scope rules of a language.

Different types of Scope:

  1. Global scope
  2. Local scope
  3. Namespace scope
  4. Class scope
  5. Statement scope
  6. Function scope
  7. Function parameter scope
  8. Enumeration scope
  9. Template parameter scope

However, the focus of this article will be on two different types of variable scope. Those are Local Variables, Global Variables.

1. Local Variables:

Local variables are those that are declared inside a function or block. Only statements included within that function or code block are permitted to use them. Outside of their own function, local variables are unknown. Here is an example of using local variables:

Code 1:

#include <iostream>
using namespace std;
 
int main () {
   // declaring local variables that can’t be accessed in outside of the block
   int m, n;
   int p;
 
   // initializing variables
   m = 20;
   n = 5;
   p = m * n;
 
   cout << p;
 
   return 0;
}

Code 2:

#include<iostream>
using namespace std;
 
void marksfunc()
{  
       // declaring local variables that can’t be accessed in outside of the function
    int marks = 95;   
}
 
int main()
{
    cout << "My annual marks is: " << marks;
     
    return 0;
}

Output:[Error]

13	39	C:\Users\X Y Z\Documents\Untitled1.cpp	[Error] 'marks' was not declared in this scope

Marks was not defined in this scope, according to the error message displayed by the software above. The variable marks was declared inside the function marksfunc(), making it specific to that function and invisible to the rest of the program.

Program Correction:

To fix the aforementioned error, we must simply show the value of the variable marks from the function marksfunc(). This is displayed in the code below:

Code:

#include<iostream>
using namespace std;


void marksfunc()
{
// declaring local variables that cant be accessed in outside of the function
	int marks = 95;
	cout <<marks;
}


int main()
{
	cout<<"My annual marks is: ";
	
	marksfunc();


	
	return 0;
}

Output:

My annual marks is: 95

2. Global Variables:

Global variables are typically defined on top of the program, outside of all the functions. The values of the global variables will remain constant over the course of your program.

Any function may access a global variable. In other words, once a global variable has been declared, it can be used throughout the entire program. The example utilizing both global and local variables is as follows:

Code:

#include<iostream>
using namespace std;
 
// declaring global variable
int global_var = 8;


//Inside a function, a global variable is accessed
void glob_display()
{
    cout << global_var << endl;
} 
 
// main function
int main()
{
    glob_display();
     
    //altering a global variable's value from the main function
    global_var = 16;
    glob_display();
}

Output:

8
16

The variable "global" in the program is declared at the beginning, outside of all the functions, making it a global variable that can be used anywhere in the program.

What if a function contains a local variable inside it with the same name as a global variable?

To further grasp the issue, take a look at the program below:

Code:

#include<iostream>
using namespace std;


// declaring global variable
int global_var = 12;


// main function
int main()
{
	//initializing local variable with the same name as global variable  
	
	int global_var = 7;
	cout << global_var << endl;
}

Have a look at the programme above. A local variable in main function declares a value of 7, but the global variable named "global_var" declares a value of 12. So what will happen when the main function prints the value that is saved in the variable called "global"? 7 or 12?

  • Usually, the compiler generates a compile time error when two variables with the same name are defined. However, the compiler permits it if the variables are specified in different scopes.
  • The compiler ensures that the local variable always has precedence over global variables when their names are same.

Output:

7

How can we access a local variable that shares the same name as a global variable?

We must utilize the scope resolution operator to resolve this issue. The program below demonstrates how to do this by use the scope resolution operator.

Code:

// C++ program to demonstrate access to a global variable


#include<iostream>
using namespace std;


// declaring global variable as var
int var = 6;


int main()
{
//  declaring local variable as var
int var = 13;


//Using the scope resolution operator " :: " , when a local variable with the same name exists
cout << "Value of global 'var' is " << ::var;


cout << "\nValue of local 'var' is " << var;
return 0;
}

Output:

Value of global 'var' is 6
Value of local 'var' is 13

Related Topics

Const Keyword in C++

The const programming language keyword will be covered in this section. The constant value that cannot change during program execution is defined using the const keywords. It implies that once...

9 minutes read.

Structure of C++ Program

Many people believe that C++, an object-oriented programming (OOP) language, is the finest language for developing demanding applications. A superset of the C language is C++. Java, a closely comparable...

4 minutes read.

Diamond Pattern using While-loop in C++

What is while Loop? A while loop or while statement repeats all code of its body as long as a specific condition is satisfied. The loop ends if or when the...

5 minutes read.

Principles of Object-Oriented Programming in C++

What is Object-Oriented Programming? Object-oriented programming is about creating obejcts that represent the real-world entity . In object-oriented programming, objects are created for the class. One of the main objectives of...

5 minutes read.

C++ Switch

In C++, an expression or variable can be tested against a range of constant values using a switch statement, which is a control flow statement. It offers a productive method...

4 minutes read.

Hexadecimal to Decimal in C++

In computers, hexadecimal numbers are represented with base 16 and decimal numbers are represented with base 10 and values 0-9, whereas hexadecimal numbers have digits ranging from 0 to 15,...

3 minutes read.

Difference between Two Sets in C++

The distinction between the two sets is made up of the components that are present in the first set but absent from the second set. The function consistently duplicates the...

3 minutes read.

Backtracking Time Complexity in C++

Introduction to Backtracking Backtracking is an important part of programming languages, and with the help of backtracking, we can do many operations in an advanced data structure. For doing major operations,...

4 minutes read.

Initialization of Data Members

In this tutorial, we'll look at how to initialise static member variables in C++. Static members, such as functions or variables, can be added to C++ classes. After declaring the...

1 minute read.

Dynamic Binding in C++

The notion of dynamic binding solved the challenges associated with static binding. Static binding refers to bindings that can be resolved by the compiler at runtime. All storage, stationary, and...

3 minutes read.

Advantage and disadvantage friend function C++

Friend Function: - A friend function in C++ is a function that can access the private, protected, and public members of a class. In C++, a friend function is a function that...

2 minutes read.

Do-While Loop Examples in C++

Before we move on the examples of Do-While loop, let’s learn little bit about the Do-While loop in C++ language. Do While loop An iterative loop that checks the condition at the...

5 minutes read.

C++ String

A string is a collection of characters. C++ programming language supports both C string as well as standard C++ library string. In C++, string is an object of std::string class. C Style String The C style...

5 minutes read.

C++ int into String

Data type conversion is a standard editing process. You may need to convert variable from one type of data to another in a variety of situations. There are two ways...

5 minutes read.

Reverse a Number in C++

In this tutorial, you'll learn how to utilize a C++ program to reverse a number entered by a user at runtime. Because there are various ways to write a C++...

3 minutes read.

Singleton Design Pattern in C++

Singleton is similar to the global variable. Singleton helps to have only one object of its kind and provides only single access. One of the key features of the singleton...

2 minutes read.

Constructor Overloading in C++

A Constructor is a class member function that is used to initialize the class's objects. Constructors have no return type and are called automatically when an object is formed. Constructor Characteristics Constructors...

3 minutes read.

How to Reverse a String in C++ using For Loop

For Loop: We may loop through a certain section of C++ code repeatedly using the for loop. A for loop is carried out if the test expression yields a true result. The...

4 minutes read.

C++ File Handling

File handling is a mechanism that manipulates the data stored in files. File handling store output data from the program to external file and read file data to the program. There...

3 minutes read.

C++ Program to find the largest number formed from an array

Given an array, write a program to find the largest number that will be formed from the elements of the array. Arrangement should be done in such a way that...

4 minutes read.