liveBook · Manning

Constant

As explained in Modern C, Third Edition

A named constant is a program constant given an identifier so code can refer to its meaning instead of repeating its value.

A named constant gives an identifier to a value with a particular meaning. Naming prevents special values from being repeated throughout a program and makes later changes easier to maintain. section 5.6

char const*const bird[3] = {
  "raven",
  "magpie",
  "jay",
};
char const*const pronoun[3] = {
  "we",
  "you",
  "they",
};
char const*const ordinal[3] = {
  "first",
  "second",
  "third",
};
...
for (unsigned i = 0; i < 3; ++i)
    printf("Corvid %u is the %s\n", i, bird[i]);
...
for (unsigned i = 0; i < 3; ++i)
    printf("%s plural pronoun is %s\n", ordinal[i], pronoun[i]);

The listing repeats the value 3 for three related arrays and loop bounds, illustrating why each meaning should receive an explanatory name. section 5.6

Use these naming rules:

  • Name every constant whose meaning matters. section 5.6
  • Distinguish constants that happen to have equal values but serve different purposes. section 5.6
  • Let a global constant identify a meaningful artifact, such as M_PI, false, true, SIZE_MAX, corvid_num, or fortytwo. section 9.2

C uses several mechanisms related to named or compile-time constants. Enumeration constants are proper named constants; macros provide text replacement and become compile-time constants only when their replacements consist of literals of base types. C23 also adds constexpr objects, while compound literals are unnamed temporary objects rather than named constants. section 5.6

How Modern C, Third Edition covers it

How deep it goes
Distinguishes enumeration constants, macros, compound literals, and C23 constexpr objects but defers their detailed mechanics.
Examples
Uses repeated array size 3, corvid_num, M_PI, false, true, SIZE_MAX, and fortytwo as naming examples.
What it assumes
Assumes familiarity with C identifiers and literals while clarifying how constants differ from variables and other program entities.
What you can do after
Apply semantic naming to replace repeated values and select among C mechanisms for named or compile-time constants.
How it connects
Connects constants with identifiers, literals, enumeration constants, macros, compound literals, and constexpr objects.

Also explained in

Compare how 3 books explain constant →

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.