HOME HTML EDITOR C JAVA PHP

C Variable Scope:

In C, **Scope** refers to the part of the program where a variable is defined and can be used. Every variable has a specific boundary. This boundary ensures that variables are only used where they are intended, protecting data from being accidentally modified by other parts of the code.

1. Local Scope (Internal Variables)

Variables declared inside a function or a block { ... } are called **Local Variables**. They can only be accessed by statements that are inside that specific function or block.

#include <stdio.h>

void myFunction() {
    int localNum = 10; // Local scope
    printf("%d", localNum); // This works
}

int main() {
    myFunction();
    // printf("%d", localNum); // ERROR: localNum not visible here
    return 0;
}

2. Global Scope (External Variables)

Variables declared outside of all functions (usually at the top of the program) are called **Global Variables**. They are accessible from any part of the program, including inside any function.

int globalCount = 50; // Global scope

void check() {
    printf("Global is: %d\n", globalCount); // Works here
}

int main() {
    printf("Global is: %d\n", globalCount); // Works here too
    return 0;
}

3. Formal Parameters

Variables used as arguments in the function definition are treated as local variables within that function. They have **Formal Parameter Scope**. They exist only during the execution of that specific function call.

4. Comparison Table: Local vs. Global

Feature Local Variable Global Variable
Declaration Inside a function/block. Outside all functions.
Accessibility Only within that function. Everywhere in the program.
Life Period Function execution time. Program execution time.
Storage Stack memory. Data segment memory.

5. Naming Conflict (Shadowing)

What happens if a local variable has the same name as a global variable? In C, the Local variable takes precedence. This is called "Shadowing." The function will use its own local version and ignore the global one.

int x = 5; // Global

int main() {
    int x = 10; // Local shadowing Global
    printf("%d", x); // Output: 10
    return 0;
}

6. The 'static' Keyword Scope

A static local variable is a special hybrid. It has the scope of a local variable (only visible in its function) but the lifetime of a global variable (it remembers its value even after the function ends).

void counter() {
    static int count = 0;
    count++;
    printf("%d ", count);
}

// If called 3 times, output is: 1 2 3
Pro Tip: Avoid using global variables unless absolutely necessary. Since any function can change a global variable, it makes debugging very difficult in large programs. In professional C development, "Encapsulation" (keeping variables local) is always preferred.