Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Mail Systems
Eclipse Documentation

How To Guides
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Problem Solutions
Privacy Policy




Thinking in C++
Prev Contents / Index Next


Here’s an example of how the two meanings of static can cross over each other. All global objects implicitly have static storage class, so if you say (at file scope),

int a = 0;

then storage for a will be in the program’s static data area, and the initialization for a will occur once, before main( ) is entered. In addition, the visibility of a is global across all translation units. In terms of visibility, the opposite of static (visible only in this translation unit) is extern, which explicitly states that the visibility of the name is across all translation units. So the definition above is equivalent to saying

extern int a = 0;

But if you say instead,

static int a = 0;

all you’ve done is change the visibility, so a has internal linkage. The storage class is unchanged – the object resides in the static data area whether the visibility is static or extern.

Once you get into local variables, static stops altering the visibility and instead alters the storage class.

If you declare what appears to be a local variable as extern, it means that the storage exists elsewhere (so the variable is actually global to the function). For example:

//: C10:LocalExtern.cpp
//{L} LocalExtern2
#include <iostream>

int main() {
  extern int i;
  std::cout << i;
} ///:~

//: C10:LocalExtern2.cpp {O}
int i = 5;

With function names (for non-member functions), static and extern can only alter visibility, so if you say

extern void f();

it’s the same as the unadorned declaration

void f();

and if you say,

static void f();

it means f( ) is visible only within this translation unit – this is sometimes called file static.

Thinking in C++
Prev Contents / Index Next

   Reproduced courtesy of Bruce Eckel, MindView, Inc. Design by Interspire