Skip to content

Global and local variables in C

2024-02-29

In C programming, variables can be classified as global and local based on their scope and lifetime.

  1. Global Variables:

    • Global variables are declared outside of any function or block, at the top of the file or in a header file.
    • Global variables have global scope, meaning they can be accessed from any part of the program, including functions, blocks, and files.
    • Global variables have static lifetime, meaning they persist throughout the entire execution of the program.
    • Global variables are initialized to zero by default if not explicitly initialized.
    • Global variables can be accessed and modified by any function or block in the program, which can sometimes lead to unintended side effects and make debugging and maintenance more challenging.

Example of a global variable:

#include <stdio.h>

int globalVar = 10; // Declaration and definition of a global variable

int main() {
    printf("Global variable: %d\n", globalVar); // Accessing global variable
    globalVar = 20; // Modifying global variable
    printf("Modified global variable: %d\n", globalVar); // Accessing modified global variable
    return 0;
}
  1. Local Variables:

    • Local variables are declared inside a function, block, or loop.
    • Local variables have local scope, meaning they can only be accessed within the function, block, or loop where they are declared.
    • Local variables have automatic lifetime, meaning they are created when the function or block is executed and destroyed when the function or block exits.
    • Local variables are not initialized to any default value, and their initial value is undefined unless explicitly initialized.
    • Local variables can only be accessed and modified within the scope where they are declared, providing better encapsulation and reducing the risk of unintended side effects.

Example of a local variable:

#include <stdio.h>

void func() {
    int localVar = 30; // Declaration and definition of a local variable
    printf("Local variable: %d\n", localVar); // Accessing local variable
    localVar = 40; // Modifying local variable
    printf("Modified local variable: %d\n", localVar); // Accessing modified local variable
}

int main() {
    func(); // Calling a function that uses local variable
    // printf("Accessing local variable outside of its scope: %d\n", localVar); // This would result in an error
    return 0;
}

It's important to use global and local variables judiciously based on the requirements and design of the program, as their scope, lifetime, and accessibilities can affect the behavior and maintainability of the code.