• Home
  • 1.25 Basic Storage-Class Specifiers

1.25 Basic Storage-Class Specifiers

View Categories

1.25 Basic Storage-Class Specifiers

1 min read

Storage-class specifiers affect the storage duration, linkage, or declaration behavior of an object or function. The commonly used C storage-class specifiers are auto, register, static, and extern.

#include <stdio.h>

int global_value = 10;

static int file_value = 20;

int main()
{
    auto int local_value = 30;
    register int counter = 40;

    printf("%d\n", global_value);
    printf("%d\n", file_value);
    printf("%d\n", local_value);
    printf("%d\n", counter);

    return 0;
}

Example Output #

10
20
30
40

Explanation #

auto declares an object with automatic storage duration. For a block-scope variable, automatic storage duration is already the default:

auto int local_value = 30;

register requests that the implementation keep the object in a processor register when appropriate:

register int counter = 40;

The compiler is not required to place the object in a register.

static has different effects depending on where it appears. At file scope, it gives an object or function internal linkage:

static int file_value = 20;

extern declares an object or function that is defined elsewhere or later in the program:

extern int global_value;

Storage-Class Specifiers #

Specifier Typical use Main effect
auto Block-scope objects Automatic storage duration
register Block-scope objects Requests register storage
static Objects and functions Static storage duration or internal linkage, depending on scope
extern Objects and functions Declares an entity with external linkage or refers to an existing definition

The meaning of static depends on declaration scope, so it is covered separately in the storage-class and linkage section.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *