Skip to content

static const is a code smell #484

@jomiller

Description

@jomiller

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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions