Detecting if an expression is constant in C
Published on: 2025-08-15 04:27:20
Detecting if an expression is constant in C
21 Apr 2025
Here's a fun little language puzzle: implement a macro that takes an expression as an argument and:
Verifies that the expression is a constant expression (i.e, known at compile time), otherwise aborts the compilation.
"Returns" back the same value.
Optionally, the returned value has the same type as the original expression.
There's a number of ways to solve this, depending on which C standard you're using and whether compiler extensions are allowed or not. Here are a few I've come across along with some pros and cons.
static compound literals
If you're using C23 or later then you can specify a storage duration for compound literals combined with typeof (also standardized in C23).
#define C(x) ( (static typeof(x)){x} )
This keeps the same type, and since initializers of static storage duration need to be constant expression, the compiler will ensure that x is a constant expression.
Cons:
Requires C23, which isn't widely
... Read full article.