Explain scope of a variable in C language.

In C programming, the scope of a variable defines where in the program that variable can be accessed or referenced. Variable scope determines the visibility and accessibility of variables throughout different parts of your program.

Syntax

// Global scope
data_type variable_name;

int main() {
    // Local scope
    data_type variable_name;
    return 0;
}

Types of Variable Scope

C language supports two main types of variable scope −

  • Local Scope: Variables declared inside a function or block are only accessible within that function or block.
  • Global Scope: Variables declared outside all functions are accessible from anywhere in the program.

Example 1: Basic Local and Global Scope

This example demonstrates the difference between local and global variables −

#include <stdio.h>

int c = 30; /* global variable */

void fun() {
    printf("Inside fun(): c = %d<br>", c); /* accessing global variable */
}

int main() {
    int a = 10; /* local variable */
    printf("Inside main(): a = %d, c = %d<br>", a, c);
    fun();
    return 0;
}
Inside main(): a = 10, c = 30
Inside fun(): c = 30

Example 2: Variable Shadowing

When a local variable has the same name as a global variable, the local variable takes precedence within its scope −

#include <stdio.h>

int x = 100; /* global variable */

int main() {
    int x = 50; /* local variable with same name */
    printf("Local x: %d<br>", x);
    
    {
        int x = 25; /* block-level local variable */
        printf("Block x: %d<br>", x);
    }
    
    printf("Main x: %d<br>", x);
    printf("Global x: %d<br>", ::x); /* Note: :: not available in C, this won't work */
    return 0;
}
Local x: 50
Block x: 25
Main x: 50

Example 3: Block Scope

Variables can also have block scope within curly braces −

#include <stdio.h>

int main() {
    int a = 10;
    printf("Before block: a = %d<br>", a);
    
    {
        int b = 20; /* block scope variable */
        a = 15;     /* modifying outer variable */
        printf("Inside block: a = %d, b = %d<br>", a, b);
    }
    
    printf("After block: a = %d<br>", a);
    /* printf("b = %d<br>", b); */ /* This would cause error - b is out of scope */
    
    return 0;
}
Before block: a = 10
Inside block: a = 15, b = 20
After block: a = 15

Key Points

  • Global variables are accessible throughout the entire program.
  • Local variables are only accessible within the function or block where they are declared.
  • Local variables hide global variables with the same name within their scope.
  • Block scope variables exist only within their enclosing curly braces.

Conclusion

Understanding variable scope in C is crucial for writing maintainable code and avoiding naming conflicts. Proper use of local and global scope helps control data access and prevents unintended variable modifications.

Updated on: 2026-03-15T13:56:59+05:30

1K+ Views

Advertisements