Skip to content
doubtly

1 answer

Best answer

Answer: C has four storage classes: automatic (auto), register, static and external (extern). They differ in storage location, default value, scope and lifetime.

A storage class tells four things about a variable: where it is stored, its default initial value, its scope (where it can be used) and its lifetime (how long it exists). C has four storage classes.

Storage classKeywordStored inDefault valueScopeLifetime
AutomaticautoMemory (stack)GarbageLocal to the block/functionTill control stays in that block
RegisterregisterCPU register (if the compiler allows), else memoryGarbageLocal to the block/functionTill control stays in that block
StaticstaticMemoryZeroLocal to the block/functionWhole program (value kept between calls)
External (global)externMemoryZeroGlobal (all functions, other files with extern)Whole program

1. Automatic: the default class for local variables. A new copy is created each time the block is entered and destroyed on exit. Example: int i; or auto int i;

2. Register: a request to keep the variable in a CPU register for faster access, useful for loop counters. Example: register int i; It is only a hint: the compiler may ignore it and keep the variable in memory. The C language does not fix a limit on the number of register variables or their type; the actual limit depends on the machine. The address operator & cannot be applied to a register variable.

3. Static: example static int count; It is initialised only once (to 0 if no value is given) and keeps its value between function calls, though it is visible only inside its function.

4. External (global): declared outside all functions, e.g. int count; at the top of the file. Any function can use it; another file can use it by declaring extern int count; The extern declaration does not create new storage, it only refers to the existing variable.

Example program:

#include <stdio.h>

int count;              /* external (global) variable: default value 0 */

void demo()
{
    auto int a = 0;     /* automatic: created afresh on every call */
    static int s = 0;   /* static: initialised once, keeps its value */
    register int r;     /* register: request to keep it in a CPU register */

    for (r = 0; r < 1; r++)
    {
        a++;
        s++;
        count++;
    }
    printf("auto a = %d, static s = %d, extern count = %d\n", a, s, count);
}

int main()
{
    demo();
    demo();
    demo();
    return 0;
}

Output (actual run):

auto a = 1, static s = 1, extern count = 1
auto a = 1, static s = 2, extern count = 2
auto a = 1, static s = 3, extern count = 3

The auto variable a starts from 0 on every call, so it is always 1. The static variable s and the global count keep their values, so they increase 1, 2, 3.

Doubtly · 27 May 2022 Report
Was this answer helpful?

Your answer

Log in or create a free account to answer this question.