liveBook · Manning

Global variable

As explained in Modern C, Third Edition

A global variable is a C object with program-wide or file-wide lifetime and visibility determined by its linkage and scope.

Two functions, one object

int visited_entries = 0; void mark_visited(void) { ++visited_entries; } int main(void) { mark_visited(); return visited_entries != 1; } The declaration of visited_entries is outside either function, at file scope. Both functions name the same object: mark_visited changes it, and main reads the changed value. section 2.2 section 10.2.2 section 9.2

A global variable is a file-scope object used as shared state. Its name is not confined to a function’s block; where it can be used depends on its scope and linkage. Function parameters, by contrast, receive values when a function is called. If two functions need to manipulate the same object rather than merely exchange values, making its declaration visible to both is one possibility. section 2.2 section 10.2.2

TAKEAWAY: Avoid a global variable when the object can instead be supplied through a function’s interface. Shared global state fixes which object a function operates on, while modifications may be scattered across the program. A function that modifies a global object—or reads changeable state other than through its arguments—is not pure: its behavior is not determined solely by its parameter values and return value. section 10.2.2

When a file-scope variable is necessary, name the state it represents. Names such as visited_entries or an initialization flag describe changing state, unlike a global constant, whose name identifies an artifact with a particular meaning. section 9.2

How Modern C, Third Edition covers it

How deep it goes
Explains file scope and the design costs of shared state, without developing linkage rules or a full global-object implementation.
Examples
Uses a shared visited_entries counter and names for initialization or error-handling state.
What it assumes
Assumes familiarity with C functions and declarations while distinguishing file scope from nested block scopes.
What you can do after
Evaluate/understand whether shared file-scope state is warranted and how it affects a function’s purity.
How it connects
Connects global variables to file scope, block scope, pass-by-value parameters, and pure functions.

Also explained in

Compare how 12 books explain global variable →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.