DEV Community

Sundar Joseph
Sundar Joseph

Posted on

Day-2: lLocal and Global Variables

local variable:
Local variables are variables that are declared within a specific scope, such as within a function or a block of code. These variables are only accessible within that particular scope and are typically used for temporary storage of data or for performing calculations within a limited context. Once the scope in which a local variable is defined ends, the variable typically goes out of scope and its memory is released.

In many programming languages, local variables have a limited visibility and lifespan compared to global variables, which are accessible from any part of the program. This encapsulation of variables within specific scopes helps to organize code, prevent unintended modifications, and manage memory efficienly

exaple of local variable
Here are the example of local variable in different language:

1

include

2
using namespace std;
3

4
void exampleFunction() {
5
// Local variable declaration
6
int x = 10;
7
int y = 20;
8
int z = x + y;
9
cout << "The sum is: " << z << endl;
10
}
11

12
int main() {
13
exampleFunction();
14
return 0;
15
}

Global variable

Global variables are variables that are declared outside of any function or block of code and can be accessed from any part of the program. Unlike local variables, which have limited scope, global variables have a broader scope and can be used across multiple functions, modules, or files within a program. Here are some characteristics, features, advantages, disadvantages, and uses of global variables:

example global variable

Here are the example of global variable in different language:

1

include

2
using namespace std;
3

4
// Global variable declaration
5
int global_var = 100;
6

7
void exampleFunction() {
8
// Local variable declaration
9
int x = 10;
10
int y = 20;
11
int z = x + y + global_var;
12
cout << "The sum is: " << z << endl;
13
}
14

15
int main() {
16
exampleFunction();
17
return 0;
18
}

Output
The sum is: 130

Top comments (0)