Local, Global and Static Variables in C

Where a variable is declared affects where it can be used and how long its stored value exists. Local variables belong to a block or function, file-scope variables can be accessed by functions in that translation unit, and a local static variable keeps its value between calls.

Global Variable Example Top ↑

#include <stdio.h>

int value = 5;

void update_value(void) {
    printf("Inside function: %d\n", value);
    value++;
}

int main(void) {
    printf("Before calls: %d\n", value);
    update_value();
    update_value();
    printf("After calls: %d\n", value);
    return 0;
}

Output

Before calls: 5
Inside function: 5
Inside function: 6
After calls: 7

The file-scope variable is the same object each function accesses, so changes remain visible after the function returns.

Local Variable Example Top ↑

#include <stdio.h>

int value = 5;

void show_local(void) {
    int value = 10;
    printf("Local value: %d\n", value);
    value++;
}

int main(void) {
    show_local();
    show_local();
    printf("Global value: %d\n", value);
    return 0;
}

Output

Local value: 10
Local value: 10
Global value: 5

Each call creates a new automatic local value. It hides the file-scope variable while execution is inside show_local().

Static Local Variable Top ↑

Key change: add static to the local declaration.

void show_count(void) {
    static int count = 10;
    printf("%d\n", count);
    count++;
}

When called twice, the output is:

10
11

A block-scope static variable is visible only in that block, but its lifetime lasts for the entire program execution.

Practice Top ↑

  1. Create a function that keeps a running total using a static local variable.
  2. Replace the static variable with a normal local variable and compare the result.
  3. Move a variable outside the function and observe how both main() and the helper function can modify it.

Continue with C functions





plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer