Difference Between Local and Global Variable

Difference Between Local and Global Variable — English

In programming, there are two types of variables — Local and Global. Both are used in different situations, and their accessibility is also different. Below is a simple and clear explanation of their differences.

Local Variable (English Explanation)

A local variable is a variable that is declared inside a function. You cannot use this variable outside that function. It becomes active only when the function is executed.

// Example of Local Variable
#include <stdio.h>

void test() {
    int x = 10;  // local variable
    printf("%d", x);
}

int main() {
    test();
    // printf("%d", x);  // ERROR: x cannot be accessed here
}

Global Variable (English Explanation)

A global variable is declared outside all functions. It can be accessed by any function in the program. Its lifetime exists throughout the entire execution of the program.

// Example of Global Variable
#include <stdio.h>

int x = 20; // global variable

void test() {
    printf("%d", x);
}

int main() {
    test();
    printf("%d", x);
}

Difference Between Local and Global Variable

Local Variable Global Variable
Declared inside a function. Declared outside all functions.
Accessible only inside that specific function. Accessible throughout the entire program.
Created when the function runs and destroyed when the function ends. Exists from program start to program end.
Consumes less memory. Memory remains occupied throughout the program.
Low chance of accidental value overwrite. Higher chance of value overwrite since many functions may modify it.

Final English Line

A local variable is limited to the function in which it is declared, whereas a global variable can be used throughout the entire program. Both have their purpose depending on the need of the program.

Comments

Popular posts from this blog

Data Abstraction

Data Abstraction

Data Structure Ka Parichay Aur Prakar (Introduction and Types of Data Structure)