Skip to content

[clang-tidy] Check request: misc-constexpr-non-static-in-scope #146296

@denzor200

Description

@denzor200

Many developers mistakenly believe that constexpr variables inside functions automatically have a static lifetime, like static variables. This common misconception leads to dangerous code that:

  • Compiles without errors, but causes undefined behavior (UB) at runtime.
  • Hard to detect in code reviews and testing.
  • Misleading because constexpr is associated with "compile-time safety".

Need a check that will find constexpr non-static variables inside a function scope. The check will provide fixit hint to add static keyword.

BEFORE:

void foo() {
   constexpr int x = 42;
   // ...
}

AFTER:

void foo() {
   static constexpr int x = 42;
   // ...
}

The check will not provide warning for constexpr variables outside a function scope:

namespace ns {
inline constexpr int MAX_SIZE = 1024;  // OK - no need static here
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions