Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction 
2.
What is a Variable?
2.1.
Syntax
3.
Scope of a Variable
4.
Local Variable
4.1.
C++
4.2.
Advantages of using Local Variable
4.3.
Disadvantages of using Local Variable
5.
Global Variable
5.1.
C++
5.2.
Advantages of using Global Variable
5.3.
Disadvantages of using Global Variable
6.
Difference Between Local Variable and Global Variable in C
7.
Frequently Asked Questions
7.1.
What is the difference between local and global environment variables?
7.2.
What is the difference between global and local variable in Postman?
7.3.
Differentiate between global and local variables in terms of scope.
7.4.
Is there any difference in the declaration of int in the global and local variables?
8.
Conclusion
Last Updated: May 16, 2024
Easy

Difference Between Local Variable and Global Variable

Author Vivek Goswami
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction 

Understanding the concepts of local and global variables is fundamental in programming, as they play a crucial role in determining the scope and lifetime of variables within a program. 

Difference Between Local Variable and Global Variable

The main difference between global and local variables is that global variables can be accessed globally in the entire program, whereas local variables can be accessed only in the block or function they are declared. 

What is a Variable?

A variable is a symbolic name given to a value or memory location that can be used to store and manipulate data within a program. Variables serve as placeholders for values that can change during the execution of a program, allowing developers to work with dynamic data.

Syntax

In most programming languages, variables are declared using a specific syntax that includes the variable name and, optionally, an initial value. The syntax for variable declaration typically follows this pattern:

data_type variable_name [= initial_value];
  • data_type: Specifies the type of data that the variable can hold, such as integer, float, string, etc.
  • variable_name: Represents the name assigned to the variable, which can consist of letters, digits, and underscores, with certain restrictions depending on the programming language.
  • initial_value: (Optional) Specifies the initial value assigned to the variable. If provided, the variable is initialized with this value; otherwise, it is left uninitialized.

For example, in Python, a variable x of type integer with an initial value of 10 can be declared as follows:

x = 10

In C++, the same variable declaration would be:

int x = 10;

Similarly, in JavaScript:

var x = 10;

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Scope of a Variable

Before beginning to understand the local and global variables, it is essential to understand the concept of the scope of a variable. The variable's scope defines where the variable would be accessible for use in the program. 

The primary difference between global and local variables lies in the scope of the two variables, which further depends on how the two variables are defined.

Read More About, C++ Basics

Local Variable

Local variables are defined within a particular program block, i.e., inside a function. They are accessible for use only inside that specific function or in the block those variables are defined. Outside the block, we cant use the variables.

Code for the declaration of local variables is as follows:

  • C++

C++

#include<bits/stdc++.h>
using namespace std;
int main()
{
int p, q, r;  // Declaring local variables p,q and r.
p=5; // Initialising value of local variable p.
q=9; // Initialising value of local variable q.
r= p*q;  // Multiplying them and declaring r with the value.
cout<<r;
return 0;
}


Output:

45

Here, the variables p,q, and r are declared inside the function - void main() in this code block. Hence, they can be used only inside the function in which they have been defined. However, we can't use these variables outside the function if another function is present in the program.

Advantages of using Local Variable

  • Limited Scope: Local variables are confined to the block or function in which they are declared, reducing the risk of naming conflicts and enhancing code readability.
  • Efficient Memory Usage: Local variables are allocated memory only when their respective block or function is executed, optimizing memory usage and reducing the likelihood of memory leaks.
  • Encapsulation: Local variables promote encapsulation by restricting access to data within a specific context, enhancing code modularity and maintainability.

Disadvantages of using Local Variable

  • Limited Accessibility: Local variables are accessible only within the block or function in which they are declared, hindering their usability in situations requiring data sharing across different parts of the program.
  • Lifetime Limitation: Local variables exist only for the duration of their enclosing block or function's execution, making them unsuitable for storing data that needs to persist beyond the scope of the block or function.

Global Variable

As the name suggests, we can access global variables throughout the program. Any function in the program can access these variables and use them.  

Following is the program illustrating the use of a global variable in C++:

  • C++

C++

#include <iostream>
using namespace std;
int p = 15;
// Declaring global variable p and initialising it with value 15.

int main()
{
int r, s; // Declaring local variables r and s.
r = 65; // Initializing value of local variable r.
s = p * r; // Initializing s as p*r.
cout << s;
return 0;
}


Output:

975


As you would have noticed in the above program, the variable p is declared outside the code block void main(); however, you can still access it by the block for various operations. The variable's scope is global, which implies that it can be used anywhere in the program by any function. The variables can be accessed and updated anywhere in the program. 

Another observation that we need to make is that, unlike local variables, these variables are not defined within a particular code block. They are defined separately in the program.

Advantages of using Global Variable

  • Accessibility: Global variables can be accessed from any part of the program, facilitating data sharing across different functions and modules.
  • Persistence: Global variables retain their values throughout the program's execution, making them suitable for storing data that needs to persist across multiple function calls.
  • Simplicity: Global variables simplify data management by providing a centralized location for storing and accessing shared data, reducing the need for passing arguments between functions.

Disadvantages of using Global Variable

  • Naming Conflicts: Global variables increase the risk of naming conflicts, especially in large projects with multiple developers, leading to unintended consequences and errors.
  • Debugging Complexity: Global variables can complicate debugging and troubleshooting efforts by introducing hidden dependencies and side effects that are not immediately apparent.
  • Security Risks: Global variables are more susceptible to security vulnerabilities, such as data tampering and unauthorized access, especially in applications exposed to external threats.

Difference Between Local Variable and Global Variable in C

ParameterLocal VariableGlobal Variable
ScopeConfined to the block or function in which they are declaredAccessible from any part of the program
LifetimeExists only within the block or function's executionPersists throughout the program's execution
AccessibilityAccessible only within the block or functionAccessible from any part of the program
Memory UsageAllocated memory dynamically when the block or function is executedAllocated memory statically when the program starts

Frequently Asked Questions

What is the difference between local and global environment variables?

In the context of software development, local environment variables are specific to a particular project or application and are accessible only within its environment. On the other hand, global environment variables are system-wide variables that are accessible across all applications and processes on a computer.

What is the difference between global and local variable in Postman?

In Postman, global variables are accessible across all requests within a collection and can be used to store and share data between requests. Local variables, on the other hand, are specific to individual requests and are not accessible outside their scope within the request.

Differentiate between global and local variables in terms of scope.

The main difference between global and local variables is that global variables can be accessed globally in the entire program, whereas local variables can be accessed only in the block or function they are declared. 

Is there any difference in the declaration of int in the global and local variables?

Yes, because when variables are defined globally, int has an initial value of 0 or one bit.
Whereas when declared locally, it has an 8-bit initial value, thus it takes more time in the definition of local variable.

Conclusion

We learned the differences Between the Local Variable and the Global Variable. Understanding the difference between local and global variables is essential for writing efficient and maintainable code. Local variables have limited scope and lifetime, confined to specific blocks or functions, while global variables are accessible throughout the entire program.

Previous article
Size of Array in C++
Next article
C++ Data Types
Live masterclass