Namespaces
Variants
Views
Actions

Storage-class specifiers

From cppreference.com
< c‎ | language
Revision as of 19:03, 11 January 2013 by 121.54.32.105 (Talk)

  • auto - automatic duration with no linkage.
  • register - automatic duration with no linkage. Also hints to the compiler to place the variable in the processor's register.
  • static - static duration with internal linkage.
  • extern - static duration with either internal or more usually external linkage.
  • _Thread_local - (since C11) - thread storage duration.

Contents

Explanation

Storage duration

All variables in a program have one of the following storage durations that determines its lifetime:

  • automatic storage duration. The variable is allocated at the beginning of the enclosing code block and deallocated at the end. This is the default for all variables, except those declared static, extern or _Thread_local.
  • static storage duration. The variable is allocated when the program begins and deallocated when the program ends. Only one instance of the variable can exist. Variables declared with static or extern have this storage duration.
  • thread storage duration (since C11). The variable is allocated when the thread begins and deallocated when the thread ends. Each thread has its own instance of the variable. Only variables declared _Thread_local have this storage duration. _Thread_local can only be declared for variables declared with static or extern and cannot be used in a function declaration.
  • allocated storage duration. The variable is allocated and deallocated per request by using dynamic memory allocation functions.

Linkage

Linkage refers to the ability of a variable or function to be referred to in other scopes. If a variable or function with the same identifier is declared in several scopes, but cannot be referred to from all of them, then several instances of the variable are generated. The following linkages are recognized:

  • no linkage. The variable can be referred to only from the scope it is in. All variables with automatic, thread and dynamic storage durations have this linkage.
  • internal linkage. The variable can be referred to from all scopes in the current translation unit. All variables which are declared static outside a local scope have this linkage.
  • external linkage. The variable can be referred to from any other translation units in the entire program. All variables which are declared either extern or const with no explicit storage-class specifier, but not static, have this linkage.

Keywords

auto, register, static, extern, _Thread_local

Example