C Programming

⌘K
  1. Home
  2. Docs
  3. C Programming
  4. Functions
  5. Local and Global Variables

Local and Global Variables

A local variable is a variable that is declared inside a function or a block and is accessible only within that function or block. It cannot be accessed outside its scope.

    Characteristics:

    • Declared inside a function or block.
    • Scope is limited to the block where declared.
    • Memory is allocated when the block is entered and deallocated when the block is exited (automatic storage).
    • Not visible outside its function.

    Example:

    #include <stdio.h>
    
    void display() {
        int x = 10;  // Local variable
        printf("x inside display(): %d\n", x);
    }
    
    int main() {
        // printf("%d", x); // Error: x not declared in this scope
        display();
        return 0;
    }

    A global variable is declared outside of all functions (usually at the top of the program) and is accessible from any function in the program.

    Characteristics:

    • Declared outside any function.
    • Scope is throughout the entire program.
    • Memory is allocated when the program starts and deallocated when the program ends.
    • Can be modified by any function (use with caution).

    Example:

    #include <stdio.h>
    
    int y = 50;  // Global variable
    
    void display() {
        printf("y inside display(): %d\n", y);
    }
    
    int main() {
        printf("y inside main(): %d\n", y);
        display();
        return 0;
    }
    Scope, Visibility, and Lifetime of Variables

    How can we help?

    Leave a Reply

    Your email address will not be published. Required fields are marked *