Local and Global Variables - GeeksforGeeks (2024)

Last Updated : 21 Mar, 2024

Improve

Local variables are declared within a specific block of code, such as a function or method, and have limited scope and lifetime, existing only within that block. Global variables, on the other hand, are declared outside of any function and can be accessed from any part of the program, persisting throughout its execution.

Table of Content

  • Local Variable
  • Example of Local Variable
  • Advantages of local variable
  • Disadvantages of local variable
  • Global Variable
  • Example of Global Variable
  • Advantages of global variable
  • Disadvantages of global variable

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 efficiently.

Example of Local Variable:

Here are the example of local variable in different language:

C++
#include <iostream>using namespace std;void exampleFunction() { // Local variable declaration int x = 10; int y = 20; int z = x + y; cout << "The sum is: " << z << endl;}int main() { exampleFunction(); return 0;}
Java
public class Main { public static void exampleFunction() { // Local variable declaration int x = 10; int y = 20; int z = x + y; System.out.println("The sum is: " + z); } public static void main(String[] args) { exampleFunction(); }}
C#
using System;public class Program { public static void ExampleFunction() { // Local variable declaration int x = 10; int y = 20; int z = x + y; Console.WriteLine("The sum is: " + z); } public static void Main(string[] args) { ExampleFunction(); }}
JavaScript
function exampleFunction() { // Local variable declaration var x = 10; var y = 20; var z = x + y; console.log("The sum is: " + z);}exampleFunction();
Python3
def example_function(): # Local variable declaration x = 10 y = 20 z = x + y print("The sum is:", z)example_function()

Advantages of local variable:

  1. Encapsulation: Local variables help encapsulate data within specific functions or blocks, reducing the risk of unintended modification.
  2. Memory Management: They promote efficient memory usage by automatically releasing memory once the scope exits.
  3. Code Clarity: Local variables make code easier to read and understand by limiting the scope of variables to where they are needed.
  4. Name Reusability: Local variables allow the reuse of variable names without causing conflicts with variables in other scopes.

Disadvantages of local variable:

  1. Limited Accessibility: Local variables cannot be accessed outside of the scope in which they are defined, which may restrict their use in certain scenarios.
  2. Potential for Shadowing Bugs: Shadowing, where a local variable hides another variable with the same name in an outer scope, can lead to bugs and confusion if not handled properly.
  3. Lifetime Limited to Scope: Local variables cease to exist once the scope in which they are defined exits, which may be a disadvantage if persistent data storage is required.

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 of Global Variable:

Here are the example of global variable in different language:

C++
#include <iostream>using namespace std;// Global variable declarationint global_var = 100;void exampleFunction() { // Local variable declaration int x = 10; int y = 20; int z = x + y + global_var; cout << "The sum is: " << z << endl;}int main() { exampleFunction(); return 0;}
Java
public class Main { // Global variable declaration static int global_var = 100; public static void exampleFunction() { // Local variable declaration int x = 10; int y = 20; int z = x + y + global_var; System.out.println("The sum is: " + z); } public static void main(String[] args) { exampleFunction(); }}
C#
using System;public class Program { // Global variable declaration static int global_var = 100; public static void ExampleFunction() { // Local variable declaration int x = 10; int y = 20; int z = x + y + global_var; Console.WriteLine("The sum is: " + z); } public static void Main(string[] args) { ExampleFunction(); }}
JavaScript
// Global variable declarationvar global_var = 100;function exampleFunction() { // Local variable declaration var x = 10; var y = 20; var z = x + y + global_var; console.log("The sum is: " + z);}exampleFunction();
Python3
# Global variable declarationglobal_var = 100def example_function(): # Local variable declaration x = 10 y = 20 z = x + y + global_var print("The sum is:", z)example_function()

Output

The sum is: 130

Advantages of global variable:

  1. Accessibility: Global variables provide a convenient way to share data across different parts of the program without passing them as function arguments.
  2. Ease of Use: They simplify the sharing of data between functions and modules, reducing the need for complex parameter passing mechanisms.
  3. Persistence: Global variables retain their values throughout the entire execution of the program, making them suitable for storing persistent data.
  4. Reduced Code Duplication: Global variables can help reduce code duplication by centralizing data that is used in multiple parts of the program.

Disadvantages of global variable:

  1. Encapsulation Issues: Global variables can lead to encapsulation issues by allowing any part of the program to modify their values, potentially leading to unintended side effects.
  2. Debugging Complexity: Since global variables can be accessed and modified from anywhere in the program, tracking down bugs related to their usage can be challenging.
  3. Potential for Race Conditions: In multithreaded or concurrent programs, global variables can introduce race conditions if accessed and modified concurrently by multiple threads or processes.
  4. Maintainability: Excessive use of global variables can make code harder to understand and maintain, as their effects may not be localized to specific functions or modules.

Conclusion:

Local variables are declared within specific blocks of code and have limited scope, existing only within their block. Global variables, declared outside of any function, are accessible from any part of the program and persist throughout its execution. It’s essential to use both judiciously, with local variables providing encapsulation and global variables offering shared data accessibility.



`; tags.map((tag)=>{ let tag_url = `videos/${getTermType(tag['term_id__term_type'])}/${tag['term_id__slug']}/`; tagContent+=``+ tag['term_id__term_name'] +``; }); tagContent+=`
`; return tagContent; } //function to create related videos cards function articlePagevideoCard(poster_src="", title="", description="", video_link, index, tags=[], duration=0){ let card = `

${secondsToHms(duration)}

${title}
${showLessRelatedVideoDes(htmlToText(description))} ... Read More

${getTagsString(tags)}

`; return card; } //function to set related videos content function getvideosContent(limit=3){ videos_content = ""; var total_videos = Math.min(videos.length, limit); for(let i=0;i

'; } else{ let view_all_url = `${GFG_SITE_URL}videos/`; videos_content+=`

View All

`; } // videos_content+= '

'; } } return videos_content; } //function to show main video content with related videos content async function showMainVideoContent(main_video, course_link){ //Load main video $(".video-main").html(`

`); require(["ima"], function() { var player = videojs('article-video', { controls: true, // autoplay: true, // muted: true, controlBar: { pictureInPictureToggle: false }, playbackRates: [0.5, 0.75, 1, 1.25, 1.5, 2], poster: main_video['meta']['largeThumbnail'], sources: [{src: main_video['source'], type: 'application/x-mpegURL'}], tracks: [{src: main_video['subtitle'], kind:'captions', srclang: 'en', label: 'English', default: true}] },function() { player.qualityLevels(); try { player.hlsQualitySelector(); } catch (error) { console.log("HLS not working - ") } } ); const video = document.querySelector("video"); const events =[ { 'name':'play', 'callback':()=>{videoPlayCallback(main_video['slug'])} }, ]; events.forEach(event=>{ video.addEventListener(event.name,event.callback); }); }, function (err) { var player = videojs('article-video'); player.createModal('Something went wrong. Please refresh the page to load the video.'); }); /*let video_date = main_video['time']; video_date = video_date.split("/"); video_date = formatDate(video_date[2], video_date[1], video_date[0]); let share_section_content = `

${video_date}

`;*/ let hasLikeBtn = false; // console.log(share_section_content); var data = {}; if(false){ try { if((loginData && loginData.isLoggedIn == true)){ const resp = await fetch(`${API_SCRIPT_URL}logged-in-video-details/${main_video['slug']}/`,{ credentials: 'include' }) if(resp.status == 200 || resp.status == 201){ data = await resp.json(); share_section_content+= `

`; hasLikeBtn = true; } else { share_section_content+= `

`; } } else { share_section_content+= `

`; } //Load share section // $(".video-share-section").html(share_section_content); // let exitCond = 0; // const delay = (delayInms) => { // return new Promise(resolve => setTimeout(resolve, delayInms)); // } // while(!loginData){ // let delayres = await delay(1000); // exitCond+=1; // console.log(exitCond); // if(exitCond>5){ // break; // } // } // console.log(loginData); /*if(hasLikeBtn && loginData && loginData.isLoggedIn == true){ setLiked(data.liked) setSaved(data.watchlist) }*/ } catch (error) { console.log(error); } } //Load video content like title, description if(false){ $(".video-content-section").html(`

${main_video['title']}

${hideMainVideoDescription(main_video['description'], main_video['id'])}

${getTagsString(main_video['category'])} ${(course_link.length)? `

View Course

`:''} `); let related_vidoes = main_video['recommendations']; if(!!videos && videos.length>0){ //Load related videos $(".related-videos-content").html(getvideosContent()); } } //show video content element = document.getElementById('article-video-tab-content'); element.style.display = 'block'; $('.spinner-loading-overlay:eq(0)').remove(); $('.spinner-loading-overlay:eq(0)').remove(); } await showMainVideoContent(video_data, course_link); // fitRelatedVideosDescription(); } catch (error) { console.log(error); } } getVideoData(); /* $(window).resize(function(){ onWidthChangeEventsListener(); }); $('#video_nav_tab').click('on', function(){ fitRelatedVideosDescription(); });*/ });

Local and Global Variables - GeeksforGeeks (2024)
Top Articles
Latest Posts
Article information

Author: Dong Thiel

Last Updated:

Views: 5637

Rating: 4.9 / 5 (79 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Dong Thiel

Birthday: 2001-07-14

Address: 2865 Kasha Unions, West Corrinne, AK 05708-1071

Phone: +3512198379449

Job: Design Planner

Hobby: Graffiti, Foreign language learning, Gambling, Metalworking, Rowing, Sculling, Sewing

Introduction: My name is Dong Thiel, I am a brainy, happy, tasty, lively, splendid, talented, cooperative person who loves writing and wants to share my knowledge and understanding with you.