The Darren Mulholland

Renowned internet personality.

Static

A bluffer's guide to the C programming language's hardest working keyword.


Back in the 1970s when the C programming language was invented, keywords were in short supply. Programmers today may find it hard to credit but at the time, with the Cold War at its height, competition for scarce keywords was fierce and often brought the world's superpowers to the brink of open conflict.

Historians agree that at no time was the spectre of war more imminent than in August of 1972 when C inventor Dennis Richie famously smuggled the last unbound keyword out of East Berlin in his beard.1 That keyword was static.

A Rented Mule

Having risked nuclear armageddon to secure control of the static keyword, the inventors of C were determined to extract the greatest possible return on their investment. Ken Thompson would later recall a jubilant Richie exhorting his colleagues at Bell Labs to "work that bitch like a rented mule".2

That's exactly what they did, and the multiple, subtly-overlapping meanings they assigned their new keyword have been confusing programmers ever since.

Storage & Linkage

Let's put the history lesson behind us for now and focus on the practicalities. The static keyword acts as a modifier for 'object' (i.e. function and variable) declarations. It's confusing because it has two different effects depending on its context - sometimes it affects the memory model used for object storage and sometimes it affects the visibility (in C terminology, the linkage) of objects.

We're going to need a little background on these topics before going any further.

Storage

C allocates storage for objects using one of three memory models: static, dynamic, or automatic.

Linkage

Objects in C are visible within one of three scopes: block scope, internal scope, or external scope. The C specification doesn't use the term 'scope', however - instead it refers to these objects as having no linkage, internal linkage, or external linkage.

Static in Action

The static modifier can be applied to:

Let's see how it affects each in turn.

Block Scope Variables

File Scope Variables

Functions

Summary

So there we have it. The static keyword means use static memory allocation, except when it doesn't, when it means give this variable or function internal linkage.

Functions and file-scope variables are statically allocated and externally linked by default; static leaves them statically allocated and makes them internally linked.

Block-scope variables are automatically allocated and have no linkage by default; static makes them statically allocated and doesn't affect their linkage.


Notes

More than 8 million Soviet peasants died in the resulting Keyword Famine, a tragedy often glossed over in Western accounts of the period.

Hampton, Wolver. (1983) Undefined Behaviour: My Years as a KGB Spy at Bell. Havana: Comintern Press.