liveBook · Manning

Global variable

As explained in Modern C

A global variable is a C variable declared outside functions whose scope extends through the remainder of its source file and whose storage normally persists for the program's execution.

A global variable is a C variable declared outside functions. Its scope extends through the remainder of its source file, and its storage normally persists for the program’s execution. A global variable identifies state rather than an artifact or action. section 9.2

Name global state so its purpose is visible:

  • toto_initialized records whether library toto has already been initialized. section 9.2
  • onError records an error condition in a file-scope internal variable that is later used during library teardown. section 9.2
  • visited_entries records shared data collected by a hash table. section 9.2

TAKEAWAY: File-scope variables are generally frowned upon, but they can be unavoidable. Their names should expose the state they represent rather than disguising it as a constant or action. section 9.2

How Modern C covers it

How deep it goes
Defines file scope, persistence, and naming practice, but stops short of implementation details.
Examples
Uses toto_initialized, onError, and visited_entries as names for initialization, error, and shared hash-table state.
What you can do after
Evaluate global-state names and recognize when file-scope variables may be unavoidable.
How it connects
Connects global variables with state, global constants, functions, and functional macros.

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. The section links point to the parts of the book it draws on.