0
0
Cprogramming~5 mins

Scope of variables

Choose your learning style9 modes available
Introduction

Scope tells us where a variable can be used in a program. It helps keep things organized and avoids confusion.

When you want to use a variable only inside a small part of your program, like inside a function.
When you want to share a variable across many parts of your program.
When you want to avoid accidentally changing a variable from another part of the program.
When you want to understand why a variable is not working as expected because it might be out of scope.
Syntax
C
/* Global variable outside functions */
int y = 10; // y is global

/* Local variable inside a function */
int main() {
    int x = 5; // x is local to main
}

void func() {
    // can use y here
}

Local variables exist only inside the block or function where they are declared.

Global variables exist throughout the whole program and can be used anywhere after they are declared.

Examples
Variable b is only available inside the inner block.
C
int main() {
    int a = 3; // a is local to main
    {
        int b = 4; // b is local to this block
    }
    // b cannot be used here
}
Function increment can use the global variable count.
C
int count = 0; // global variable

void increment() {
    count = count + 1; // can access global count
}
Variable x is local to func and not visible in main.
C
void func() {
    int x = 10; // local to func
}

int main() {
    // x cannot be used here
}
Sample Program

This program shows how local_var is only available inside show(), but global_var can be used anywhere.

C
#include <stdio.h>

int global_var = 100; // global variable

void show() {
    int local_var = 50; // local variable
    printf("Inside show(): local_var = %d\n", local_var);
    printf("Inside show(): global_var = %d\n", global_var);
}

int main() {
    show();
    // printf("In main(): local_var = %d\n", local_var); // This would cause error
    printf("In main(): global_var = %d\n", global_var);
    return 0;
}
OutputSuccess
Important Notes

Trying to use a local variable outside its scope will cause a compile error.

Global variables can make programs harder to understand if overused, so use them carefully.

Blocks inside functions (like inside braces {}) can have their own local variables too.

Summary

Scope defines where a variable can be accessed in a program.

Local variables live inside functions or blocks and cannot be used outside.

Global variables live throughout the program and can be used anywhere after declaration.