Chapter 29 of 37

Scope and Lifetime

When working with variables, two important questions come up:

  • Where can I access this variable?

  • How long does this variable exist?

These are called scope and lifetime.

What is Scope?

Scope is the region of a program where a variable, function, or other identifier can be accessed.

For example:

void test()
{
    int age = 20;

    printf("%d", age);
}

Here, age can be accessed only inside the test() function.


Types of Scope

C mainly has four kinds of scope:

Scope

Meaning

Block scope

Available inside a block { }

Function scope

Applies to labels inside a function

Function prototype scope

Applies to parameter names in a function prototype

File scope

Available from its declaration to the end of the source file

For beginners, block scope and file scope are the most important.

Block Scope

A variable declared inside a block is accessible only within that block.

int main()
{
    int age = 20;

    if (age >= 18)
    {
        int x = 10;
        printf("%d", x);
    }

    // x cannot be accessed here
}

File Scope

A variable declared outside all functions has file scope:

int count = 10;

int main()
{
    printf("%d", count);
}

count is visible from its declaration to the end of the source file, subject to linkage rules.


What is Lifetime?

Lifetime is the period during program execution for which an object exists in memory.

For example, a normal local variable:

void test()
{
    int x = 10;
}

comes into existence when the function's block is entered and ceases to exist when that block is left.


Scope vs Lifetime

These two concepts are related but different.

Scope

Lifetime

Where a variable can be accessed

How long the variable exists

Concerned with visibility

Concerned with existence

Determined by the program's structure

Determined by storage duration

For example:

void test()
{
    static int x = 10;
}

x has block scope, so it can only be accessed inside test(), but its lifetime lasts for the entire execution of the program.

That's a great example of why scope and lifetime are not the same thing.

Simple Example

int global = 100;

void test()
{
    int local = 20;

    printf("%d %d", global, local);
}

Here:

  • global → file scope and normally has static storage duration.

  • local → block scope and automatic storage duration.

In Simple Words

Scope tells you where a variable can be used, while lifetime tells you how long that variable exists.

A simple way to remember:

Scope → Where?

Lifetime → How long?

Understanding these concepts will make topics like static, extern, functions, and storage classes much easier to understand.