I am quite surprised that C does not guarantee that certain (constant) expressions are evaluated at compile (translation) time.
C11 (6.6 Constant expressions) (emphasis added):
A constant expression can be evaluated during translation rather than runtime, ...
Hence, two questions:
- Is there a standard way to guarantee that a certain (constant) expressions will be evaluated at compile (translation) time?
- Extra question: why C does not guarantee it? What were the (technical) obstacles to guarantee it?
UPD20230711. In _Static_assert
declaration an integer constant expression is required to be evaluated at translation time, because per Semantics section (C11, 6.7.10p3) an implementation checks whether the constraint is violated. If the constraint is violated, then the implementation is required to produce a diagnostic message. If the diagnostic message is produced at translation time, then the integer constant expression is evaluated at translation time. This means that in some contexts a constant expression can (i.e. not required) be evaluated at compile (translation) time (e.g. switch(<const_expr>)
, in other contexts a constant expression shall (i.e. required) be evaluated at compile (translation) time (e.g. _Static_assert (<const_expr>, "");
.