Difference between Local Variable and Global Variable in C

1. Introduction

In C programming, variables can be classified as local or global based on their scope and lifetime. Local variables are declared inside a function or block and can only be used within that function or block. Global variables are declared outside all functions, usually at the top of a program file, and can be accessed from any function within the file.

2. Key Points

1. Local variables have a scope limited to the function or block in which they are declared.

2. Global variables are accessible from any part of the program after their declaration.

3. The lifetime of a local variable is limited to the execution of the function or block.

4. Global variables exist throughout the lifetime of the program.

3. Differences

Local Variable Global Variable
Declared within a function or block. Declared outside of all functions, typically at the top of the file.
Scope is limited to the function or block where it is declared. Accessible throughout the program from any function after its declaration.
Lifetime is limited to the execution of the function or block. Lifetime is throughout the program's execution.

4. Example

#include <stdio.h>

int globalVar = 10; // Global variable

void function() {
    int localVar = 20; // Local variable
    printf("Inside function, localVar: %d, globalVar: %d\n", localVar, globalVar);
}

int main() {
    printf("In main, globalVar: %d\n", globalVar);
    function();
    // printf("In main, localVar: %d\n", localVar); // This would cause a compile-time error
    return 0;
}

Output:

In main, globalVar: 10
Inside function, localVar: 20, globalVar: 10

Explanation:

1. globalVar is accessible both in the main function and inside function.

2. localVar is only accessible within function and trying to access it in main would result in a compile-time error.

5. When to use?

- Use local variables for temporary storage that is only relevant within a certain block or function.

- Use global variables for data that needs to be accessed by multiple functions throughout a program.

Comments