Friday, July 16, 2010

Storage Class Specifiers

Excerpts are from an excellent article by Dan Saks from CUJ November 1997 Titled "Storage Classes and Linkage" There are three types of Decl-Specifiers
  1. Storage Class Specifiers(extern, static, mutable, auto, register)
  2. Type Specifiers(float, int, unsigned...)
  3. Function Specifiers(virtual, inline)
Every object and function declaration has two parts:
  1. decl-specifier-sequence(a sequence of decl-specifiers in any order)
  2. declarator-list(a comma-separated list of one or more declarators)
There can be more than one type specifier in the declaration but we can not have more than one storage specifier unsigned long int *p; //Is Valid extern mutable int value;//Is invalid In C++ a declaration introduces a name into a program, and specifies attributes for that name. If the declarator-id in the declaration designates an object or function, and the declaration reserves storage for that object or function then that declaration is also a definition. Rules of thumb
  1. A function declaration is a definition if it includes the function's body.
  2. An object declaration is a definition unless
    1. It contains the extern specifier with no initializer
    2. It declares a static data member in a class declaration
C and C++ provide for three levels of linkage
  1. A name with external linkage denotes an entity that can be referenced via names declared in other scopes in the same or different translation units
  2. A name with internal linkage denotes an entity that can be references via names declared in other scopes in the same translation unit
  3. A name with no linkage
Linkage at namespace scope
  • if a symbol has no storage class or it has extern specifier it has external linkage
  • if it has static specifier it has internal linkage
  • if it is using const specifier it has internal linkage by default unless it is also using extern (it has to be initialized because it is const! unless it is using extern and it makes sense!)
Rules of thumb
  • An object or function has internal linkage if it is explicitly declared static or previously declared with internal linkage
  • A const object has internal linkage if it is neither explicitly declared extern nor previously declared with external linkage
  • Otherwise and object or function at namespace scope has external linkage
In the block scope there is no linkage unless we use extern

No comments:

Post a Comment