×

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

Swap numbers in C++

Swap numbers Swapping refers to interchanging values between two variables. Swapping is important and easy to understand programming logic in the world of coding. Though it is used in the programming...

4 minutes read.

Storage Classes in C

Storage Classes in C Storage Classes are used to define the variable and function property. These functionalities include basically the scope, accessibility, and lifetime that help us detect the existence of...

4 minutes read.

ATM machine program in C++ using functions

Automated Teller Machines (ATMs) carry out daily financial transactions. They are straightforward and simple, allowing customers to complete self-service transactions quickly. ATMs can then be used to withdraw cash, deposit...

3 minutes read.

C++ Multimap

Definition: In C++, a multimap is similar to a map with the additional concept, where multiple elements possess the same keys. It is also not necessary that the key values and...

4 minutes read.

How to make a password program in C++

Before understanding the password program, one must know about a password and why it is required. Password: A password is a word that permits access to somewhere or something. A password...

4 minutes read.

C++ Friend function

A friend function has the right to access all private and protected members of a class although it is defined outside that class' scope. Syntax class className{     ......     friend retyrn_type function_Name(argument);     .......   }   return_type function_Name(argument){     ......   } C++ friend function Example #include <iostream>   using namespace std;   class Length   {       private:           int meter;       public:           Length(): meter(5) { }           friend int addMethod(Length); //friend function declaration   };   int addMethod(Length l) // friend function definition   {       l.meter += 10; //accessing private data from non-member function       return l.meter;   }   int main()   {       Length L;       int totallength;       totallength=addMethod(L);       cout<<"Length: "<< totallength;       return 0;   } Output: Length: 15   C++ friend function...

1 minute read.

goto statement in C and C++

goto statement in C and C++ The goto statement is a jump statement, also sometimes referred to as an unconditional jump statement. Within a function, the goto statement can be used...

3 minutes read.

C++ array to function

Arrays in C++ : Instead of defining distinct variables for each item, arrays are used to hold numerous values in a single variable. An array can be declared by specifying the variable...

4 minutes read.

Include Guards in C++

In C++ programming, we frequently utilize a class more than once, so it is necessary to create a header file and include it in the main program. Now, occasionally a...

3 minutes read.

List back () function in C++ STL

The list::back () function of the C++ STL returns a direct reference to the last element in the list container. This function varies from list::end (), which just returns an...

2 minutes read.

LCM Program in C++

What is LCM? LCM is an acronym for "least common multiple". It is used to discover the lowest positive integer divisible by all integers (whose LCM is calculated). For instance, the...

4 minutes read.

Similarities between C++ and Java

People who are preparing for software engineering roles must have come across either one of these languages because as all the companies do not accept python for hiring a fresher...

3 minutes read.

C++ Continue in Do-while loop

Continue statement: Inside the loop, the continue statement is used to control the loop. C++ utilizes the continue keyword to implement the continue statement, which transfers the program's flow at the start...

4 minutes read.

C++ Global Variable

In C++, a global variable is a variable that is defined outside of any function or class and can be accessed by any function or class in the program. Global...

4 minutes read.

C ++ Program: Alphabet Triangle and Number Triangle

Alphabet Triangle and Number Triangle An alphabet triangle is a triangle that typically looks like a pyramid or other triangles like an isosceles triangle, a right-angled triangle consisting of similar or...

4 minutes read.

Inheritance Program in C++

What is Inheritance? Inheritance is the ability of a class to inherit traits and properties from another class. One of the most crucial aspects of Object-Oriented Programming is inheritance. The ability or...

9 minutes read.

Function Pointer in C++

Definition: A function pointer in C++ is the same as a usual pointer which is used to point some variables. Function pointers are used to point functions or say store the...

4 minutes read.

C++ Convert Int to String

In fact, the conversion of numbers to strings or vice versa represents a significant paradigm change. We often need to convert a number to a string or a string to...

2 minutes read.

C++ String Class and its Applications

The String class is available in C++. The character array is represented by the C string. The string class in C++ has a few different attributes. It contains several functions...

4 minutes read.

Factory Method for Designing Pattern in C++

In C++, the factory method is a type of conditional design pattern. The factory method is related to creating a new object in C++. With the help of a factory...

3 minutes read.