C++ Variable Scope

Hi everyone, inside this article we will see about C++ Variable Scope.

In C++, the scope of a variable determines the part of the program where the variable can be accessed.

Types of Scope

There are two main scopes in C++:

Local scope

A local scope refers to the area within a function where a variable is defined. Variables defined within a function have local scope and are only accessible within the function.

Here is an example of a C++ program that demonstrates the use of local scope variable.

#include <iostream>
using namespace std;

void printVariable() {
   int localVariable = 10; // local scope variable
   cout << "Value of localVariable: " << localVariable << endl;
}

int main() {
   printVariable();
   return 0;
}

Output

Value of localVariable: 10

In this program, the variable localVariable is defined within the function printVariable, so it has local scope. The value of localVariable is printed within the function, and it can be accessed only within that function. If you try to access localVariable from outside of the function, the compiler will report an error.

Global scope

A global scope refers to the area outside of all functions. Variables defined outside of any function have global scope and can be accessed from any part of the program.

Here is an example of a C++ program that demonstrates the use of global scope variables:

#include <iostream>
using namespace std;

int globalVariable = 10; // global scope variable

void printVariable() {
   cout << "Value of globalVariable: " << globalVariable << endl;
}

int main() {
   printVariable();
   return 0;
}

Output

Value of globalVariable: 10

In this program, the variable globalVariable is defined outside of any function, so it has global scope. The value of globalVariable is printed within the function printVariable, and it can be accessed from any part of the program. Because globalVariable has global scope, it persists throughout the lifetime of the program and retains its value even after the function printVariable has returned.

We hope this article helped you to understand about C++ Variable Scope in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.