0
0
Cprogramming~5 mins

Lifetime and scope comparison

Choose your learning style9 modes available
Introduction

Lifetime and scope tell us where and how long a variable can be used in a program. This helps us keep our code organized and avoid mistakes.

When deciding where to declare a variable to keep it safe from unwanted changes.
When you want a variable to keep its value even after a function ends.
When you want to limit a variable so only part of the program can use it.
When debugging to understand why a variable is not accessible or losing its value.
When managing memory and resources carefully in bigger programs.
Syntax
C
/* Scope examples */
int global_var; // global scope

void function() {
    int local_var; // local scope
}

/* Lifetime examples */
static int static_var; // lifetime lasts entire program
int normal_var; // lifetime lasts entire program

Scope means where in the code a variable can be accessed.

Lifetime means how long the variable exists in memory.

Examples
Global variables can be used anywhere. Local variables only exist inside the function.
C
int global_var; // global scope, lifetime is whole program

void func() {
    int local_var; // local scope, lifetime is during func call
}
Static variables keep their value between function calls, so their lifetime is the whole program but scope is local.
C
void func() {
    static int count = 0; // static variable
    count++;
    printf("Count: %d\n", count);
}
Sample Program

This program shows how global_var is accessible everywhere, local_var only inside demo(), and static_var keeps its value between calls.

C
#include <stdio.h>

int global_var = 10; // global scope and lifetime

void demo() {
    int local_var = 5; // local scope and lifetime
    static int static_var = 0; // local scope, lifetime whole program
    static_var++;
    printf("Inside demo - global_var: %d, local_var: %d, static_var: %d\n", global_var, local_var, static_var);
}

int main() {
    demo();
    demo();
    // printf("local_var: %d\n", local_var); // Error: local_var not visible here
    printf("global_var in main: %d\n", global_var);
    return 0;
}
OutputSuccess
Important Notes

Global variables have global scope and lifetime for the whole program.

Local variables have scope only inside their block and lifetime only during that block execution.

Static local variables have local scope but lifetime for the whole program.

Summary

Scope controls where a variable can be used in the code.

Lifetime controls how long a variable exists in memory.

Static variables combine local scope with long lifetime.