Constants, constant expressions, and compile-time checks
Choose between literals, enumeration constants, macros, const objects, and C23 constexpr with the right contract.
In this chapter10 sections
A value that does not change during one run is not automatically a value C accepts in every compile-time context. This chapter separates literals, read-only objects, and constant expressions so the word constant stops hiding several different rules.
1. Four ways to write a fixed-looking value
| Form | What it provides in C17 | Useful when |
|---|---|---|
4 | An integer constant token with a type determined by its spelling and range | The value is clear locally. |
enum { COUNT = 4 }; | A named enumeration constant; here its type is int | A small named integer is needed in constant-expression contexts. |
#define COUNT 4 | Preprocessing token replacement, not a typed object declaration | A preprocessing decision needs the spelling, or an established interface uses a macro. |
const int count = 4; | A typed, read-only object; ordinary reads are not integer constant expressions | The program needs an object with read-only access. |
A Constant expression belongs to a language-defined category. The category is not decided by whether a compiler can optimize the expression to one value. A macro can expand to a constant expression, a function call, or something else; the expansion determines the result.
2. Integer constant expressions fit specific contexts
#define COLUMN_COUNT 4
enum { ROW_COUNT = 3 };
const int selected_row = 1;
int values[ROW_COUNT][COLUMN_COUNT] = { { 0 } };
_Static_assert(ROW_COUNT * COLUMN_COUNT == 12, "grid contract");
values[selected_row][2] = 7;
#undef COLUMN_COUNT
ROW_COUNT and the macro-expanded COLUMN_COUNT provide constant array bounds. selected_row is a const object used during ordinary indexing; it need not be a constant expression. The static assertion checks the 12-element design at translation time. The array and indexing are a small preview; understanding arrays develops their boundaries.
C17 integer constant expressions have integer type and restricted operands: integer/enumeration/character constants, suitable sizeof results and _Alignof expressions, plus the specified limited casts and unevaluated-operand exceptions. Function calls, assignments, increments, and comma operators do not generally belong in evaluated constant expressions. Do not reduce the rule to “only literal numbers,” or to “anything pure.”
Case labels, enumeration values, static assertions, and non-VLA array bounds have constant-expression requirements with their own further constraints. They are not interchangeable with an arbitrary runtime int.
Intentional diagnostic: a const object is not a C17 integer constant expression
const int count = 4;
_Static_assert(count == 4, "not an integer constant expression in C17");
The initializer being 4 does not change the classification of count's read. Use an enumeration constant here in C17, or an appropriate C23 constexpr object under C23 rules.
3. Storage duration does not make every initializer valid
C17 initializers for static/thread-duration objects must use constant expressions or string literals as specified by the initialization rules. Their permitted forms include more than integer constant expressions: for example, an address constant can initialize a pointer to an object with static duration.
#include <assert.h>
static int object;
static int *saved_address = &object;
int main(void)
{
assert(saved_address == &object && *saved_address == 0);
return 0;
}
saved_address is initialized with the address of the existing static object. This is not evidence that an ordinary function call is allowed as a C17 static initializer. Likewise, a const declaration does not automatically make a later use valid as a file-scope array bound.
Intentional diagnostic: a variable length array at file scope
const int count = 4;
int values[count];
In C17, count is an object, so the array bound is not an integer constant expression. The resulting variably modified type is not allowed at file scope. Inside a block, a variable length array is a different feature with its own optional-support and positive-bound requirements; adding const does not turn it into a fixed-size array.
4. A mentioned expression need not execute
int value = 3;
size_t width = sizeof(value++);
The operand has type int, so sizeof yields its size in C bytes without evaluating value++. value remains 3. The result has type size_t. This particular sizeof result is an integer constant; with variable length array types, size computation can involve runtime evaluation and the standard has additional exceptions.
The C17 operator _Alignof(type-name) queries a type's alignment. It is not a runtime probe that tries a pointer access. A constant-expression requirement and an unevaluated operand are related language rules, not permission to insert arbitrary invalid syntax.
5. #if sees preprocessing information, not C objects
A preprocessing condition such as #if COLUMN_COUNT == 4 can use the expanded macro tokens. The preprocessor does not look up ordinary const objects or enumeration constants. After macro replacement and the specified processing, remaining identifiers in a C17 #if expression are replaced by zero. A misleading condition can therefore select the wrong branch while the later C declaration looks correct.
Use preprocessing to choose source/configuration before translation. Use _Static_assert for C type/value contracts that meet its requirements. Use a runtime check for values only known during execution. A runtime assert can be disabled by NDEBUG; it should not be the only validation for untrusted input or an operation whose side effect must occur.
6. C23: constexpr adds a named constant object
In C23, constexpr int count = 4; defines a const-qualified object whose identifier can participate in appropriate constant expressions. For example, static_assert(count == 4); is a C23 illustration. C23 also permits the single-argument static_assert form; C17's _Static_assert requires the message argument.
Constexpr is an object feature in C23, not the C++ feature for defining constexpr functions. Initializers and object types must meet its constraints, including the relevant exact-representability requirements. Arbitrary calls do not become valid constant initializers. A block constexpr object without static can still have automatic duration; a file-scope constexpr identifier has internal linkage. Read-only access, constant-expression use, linkage, and duration remain distinct.
These inline C23 forms are source-reviewed version notes. The runnable examples on this page use C17; check actual compiler and library support before adopting newer forms in a project.
7. Thought check: can the optimizer change a language rule?
A compiler folds a const object read to 4. Does that make it a C17 case-label constant?
No. Optimization can change how an implementation executes a valid program; it does not make an expression satisfy a source-language constant-expression requirement. Choose a form the selected standard admits, then optimize only within those rules.
Sources and further reading
Primary references: WG14 N1570 6.4.4, 6.5.3.4, 6.6, 6.7.9, 6.7.10, and 6.10.1; WG14 N3096 (C23 notes). These are public committee drafts; the examples here use a C17 baseline.
Before you move on
- Literals, enumeration constants, read-only objects, and constant expressions are distinct categories.
- A context may require an integer constant expression rather than merely an unchanged runtime value.
- C23 constexpr objects follow their own rules and do not supply C++ constexpr functions.
Keep these ideas separate
- const / Constant expression
- An ordinary const object is not automatically an integer constant expression in C17.
Why can two declarations with the same numeric value be accepted in different compile-time contexts?
Optional: say it aloud or keep a note. You can continue whenever you are ready.Check your understanding
Optional. Answers are not saved or sent, and reading stays unrestricted.
Read the explanation for every choice
- Yes, const has the same role as every compile-time constant facility.
Read-only qualification and integer-constant-expression rules are different concepts.
- No. const qualification alone does not satisfy that rule.
✓ Correct reasoning. Use a form allowed by the relevant constant-expression context, such as an appropriate enumerator or integer constant.
- It makes every array using n invalid in every context.
A nonconstant bound can instead form a VLA where that facility and context are supported.
C17
Ready for the next idea?
Mark this chapter as read whenever you feel ready.