C Scope and Storage Classes

Scope tells where a variable can be used. Storage class tells how long it lives and where it is stored.

Local and global variables

TypeDeclaredCan be usedDefault value
LocalInside a function or blockOnly in that blockGarbage value
GlobalOutside all functionsEverywhere after the declaration0
#include <stdio.h>

int total = 100;      // global

void show(void) {
    int local = 5;    // local to show()
    printf("%d %d\n", total, local);
}

int main(void) {
    show();
    total = 200;
    show();
    return 0;
}

Output:

Output of the above program is

100 5
200 5

If a local variable has the same name as a global one, the local variable is used inside the function.

Storage classes

ClassMeaning
autoDefault for local variables. Created when the block starts and removed when it ends.
staticKeeps its value between function calls. Initialized only one time.
externTells that the variable is defined in another file or later.
registerA hint to keep the variable in a CPU register for speed. The compiler may ignore it.

static example

#include <stdio.h>

void counter(void) {
    static int count = 0;
    int normal = 0;

    count++;
    normal++;
    printf("static=%d normal=%d\n", count, normal);
}

int main(void) {
    counter();
    counter();
    counter();
    return 0;
}

Output:

Output of the above program is

static=1 normal=1
static=2 normal=1
static=3 normal=1

Note: Use global variables as little as possible. Many functions can change them, so bugs are hard to find. Prefer passing values as arguments.

Next: C Arrays.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
Write a C program to find the factorial of a number using recursion
Write a C program to swap two numbers using a function and pointers
Interview Questions & Answers
What is the difference between call by value and call by reference in C?
What is recursion in C?
What is the difference between local and global variables in C?
What are storage classes in C?
What is the use of the static keyword in C?