Code Skiller logoCB Logo
Logo LearnLearnLogo PracticePracticeLogo HireHireLogo IDEIDE

Scope of a Variable | Lifetime and Visibility

User image

Published by

sanya sanya

Published at: 27th Jul, 2023
2.095 mins read

What is the scope of a variable?

The scope of a variable refers to the region or portion of the program where the variable is visible and can be accessed. It defines the lifetime and visibility of the variable within the program.

Relevance of variable scope:

Understanding variable scope is crucial for writing clean and maintainable code. By limiting the visibility of variables to the necessary parts of the program, you reduce the risk of naming conflicts and improve code readability. Additionally, it helps manage memory efficiently by allowing variables to be deallocated when they go out of scope.

Examples with code:

Example 1: Local Variable Scope

#include

using namespace std;

void myFunction() {

int x = 5; // Local variable

cout << x << endl;

} // x goes out of scope here

int main() {

myFunction();

// x is not accessible here

return 0;

}

In this example, the variable ‘x’ is declared within the ‘myFunction()’ function. It has a local scope, meaning it is only accessible within the function in which it is declared. Once the function ‘myFunction()’ finishes execution, the variable ‘x’ goes out of scope and is no longer accessible.

Example 2: Global Variable Scope

#include using namespace std;

int x = 5; // Global variable

void myFunction() {

cout << x << endl; // Access global variable x

}

int main() {

myFunction();

cout << x << endl; // Access global variable x

return 0;

}

In this example, the variable ‘x’ is declared outside of any function, making it a global variable. Global variables have a scope that extends throughout the entire program, and they can be accessed from any function within the program.

Example 3: Block Scope

#include

using namespace std;

int main() {

int x = 5; // Variable with block scope

if (x == 5) {

int y = 10; // Variable with block scope

cout << x + y << endl;

} // y goes out of scope here

// y is not accessible here

return 0;

}

In this example, both variables ‘x’ and ‘y’ have block scope. The variable ‘x’ is declared in the main function, while ‘y’ is declared within the if statement block. Variables with block scope are only accessible within the block in which they are declared. Once the block ends, the variables go out of scope and cannot be accessed.

Library

WEB DEVELOPMENT

FAANG QUESTIONS