liveBook · Manning

Integer constant expression

As explained in Modern C

An integer constant expression is a C expression whose value is an integer constant determined according to the language's constant-expression rules.

An integer constant expression (ICE) is a restricted C expression whose integer value is determined at compile time. It cannot call a function or evaluate an object as an operand. Integer literals and enumeration constants can participate; _Alignof, offsetof, and some sizeof expressions may also qualify. section 5.6.2

Literal versus object

signed const o42 = 42; enum { b42 = 42, // OK: literal c52 = o42 + 10, // Error: evaluates an object b52 = b42 + 10, // OK: enumeration constant }; TAKEAWAY: const qualification does not make an object usable in an integer constant expression. section 5.6.2

The restriction matters directly in switch statements: every case value must be an integer constant expression. A variable such as count may control switch, but cannot serve as an individual case value. section 3.3

enum corvid { magpie, raven, jay, corvid_num, };
char const*const bird[corvid_num] = {
  [raven]  = "raven",
  [magpie] = "magpie",
  [jay]    = "jay",
};
...
for (unsigned i = 0; i < corvid_num; ++i)
    printf("Corvid %u is the %s\n", i, bird[i]);


!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":0,\"ch\":0},{\"line\":0,\"ch\":4}],[{\"line\":1,\"ch\":0},{\"line\":1,\"ch\":10}],[{\"line\":1,\"ch\":5},{\"line\":1,\"ch\":10}],[{\"line\":7,\"ch\":0},{\"line\":7,\"ch\":3}],[{\"line\":7,\"ch\":5},{\"line\":7,\"ch\":13}],[{\"line\":8,\"ch\":4},{\"line\":8,\"ch\":10}]]"}
!@%STYLE%@!

Browse an enumeration and indexed string array using compile-time enumeration constants such as raven, magpie, jay, and corvid_num. section 5.6.2

How Modern C covers it

How deep it goes
Defines compile-time evaluation and object exclusion, while deferring _Alignof, offsetof, and sizeof details.
Examples
Uses switch case labels, enumeration declarations, indexed arrays, and valid-versus-invalid enumeration initializers.
What you can do after
Apply it in C by distinguishing compile-time integer expressions from expressions that evaluate objects.
How it connects
Links integer literals, enumeration constants, switch statements, _Alignof, offsetof, and sizeof.

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