cpp_weekly icon indicating copy to clipboard operation
cpp_weekly copied to clipboard

`static const` is a code smell

Open jomiller opened this issue 7 months ago • 2 comments

Channel

C++Weekly

Topics

static const variables look innocuous, but they can have subtle correctness and performance issues, especially for local (function scope) variables. We've been taught to constexpr all the things, and that static constexpr is the preferred form for local variables (see Ep 312). However, when static constexpr doesn't compile (because the right-hand side is not a constant expression), the average programmer might fall back to static const thinking it's the next best thing.

Here's an example correctness bug that static const causes:

void frobnicate(int value)
{
    // twiddledValue is initialized with the first `value` passed in and never changes afterwards
    static const auto twiddledValue = twiddle(value);
}

In terms of performance, the compiler often inserts a guard variable to protect the static variable's initialization, which adds some run-time overhead. (I'm not sure under which circumstances this occurs. Is it when the expression is not a "core constant expression" so it's not evaluated at compile time?)

Length

5-10 minutes

jomiller avatar Jun 05 '25 00:06 jomiller

Isn't it already covered in episode 2: https://www.youtube.com/watch?v=B3WWsKFePiM ?

Dharmesh946 avatar Jun 06 '25 08:06 Dharmesh946

Isn't it already covered in episode 2: https://www.youtube.com/watch?v=B3WWsKFePiM ?

Fair enough. There might not be enough substance for another episode. I was thinking to cover it from the perspective of being deceptively similar-looking to static constexpr.

jomiller avatar Jun 06 '25 13:06 jomiller