liveBook · Manning

Integer constant expression

As explained in Modern C, Third Edition

An integer constant expression is a C expression whose value can be determined during translation using only permitted constant operands and operations.

In `switch (count)`, `count` may vary, but each `case` value must be an integer constant expression (ICE). Values such as `case 4:` qualify; a variable such as `count` cannot supply a case value. Case values must also be unique within the switch. section 3.3

An ICE provides an integer value determinable during translation. That is not enough by itself: a function call cannot supply the value, and an ordinary object cannot participate in its evaluation, even if it is `const`-qualified. Integer literals and enumeration constants can be used; an object declared with `constexpr` can also participate. section 5.6.2

signed const     o42 = 42;
constexpr signed c42 = 42;
enum {
  b42 = 42,       // Ok: 42 is a literal.
  c52 = o42 + 10, // Error: o42 is an object.
  b52 = b42 + 10, // Ok: b42 is not an object.
  d52 = c42 + 10, // Ok: c42 is a named constant.
};

Compare `b52`, formed from an enumeration constant, with the invalid `c52`, formed from a `const` object. `d52` is valid because `c42` is declared with `constexpr`. section 5.6.2

Enumeration constants can name values used in further enumeration initializers. An enumeration count can also appear as an array bound, avoiding a separately tracked numeric size. TAKEAWAY: A value being known to a reader—or stored in a `const` object—does not alone make its expression an ICE. section 5.6.2

How Modern C, Third Edition covers it

How deep it goes
Defines compile-time and object-evaluation restrictions through valid and invalid examples, without providing a complete grammar of permitted expressions.
Examples
Contrasts literal case labels with a variable and tests enumeration initializers built from literals, enum constants, const objects, and constexpr objects.
What it assumes
Assumes familiarity with C expressions and declarations while explaining the distinction between ordinary const objects and constexpr objects.
What you can do after
Evaluate/understand whether a proposed case value or enumeration initializer meets the illustrated ICE restrictions.
How it connects
Connects switch statements, enumeration constants, const-qualified objects, constexpr objects, and array bounds.

Also explained in

Compare how 2 books explain integer constant expression →

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.