C++ Logo

std-proposals

Advanced search

Re: [std-proposals] compile_assert() a static assert that fires at compile time, not runtime.

From: Jonathan Wakely <cxx_at_[hidden]>
Date: Thu, 19 Feb 2026 15:33:24 +0000
On Thu, 19 Feb 2026 at 15:24, Alejandro Colomar via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> Hi Jan,
>
> On 2026-02-19T16:11:54+0100, Jan Schultke via Std-Proposals wrote:
> > I can't bring myself not to think of it as a "false positive".
> > compile_assert is asking the question "Is it known at compile time that
> > this condition is true?"
> >
> > There are cases where the answer is yes, but the compiler can't prove it,
> > so it explodes and gives you a false positive diagnostic.
> >
> > One could say that this feature has no false positives and false
> negatives
> > when phrasing what compile_assert does in terms of compiler mechanics,
> but
> > that doesn't seem helpful. When the compiler gives you an error when it
> > theoretically shouldn't, and it only does so due to
> > insufficient cleverness, that's a false positive to me. We treat compiler
> > warnings as a false positive when that happens.
>
> Some correction: this has false positives, in the sense that when
> compiling with too-low optimization level you'll get unnecessary errors.
> But it has absolutely no false negatives. You'll never get a successful
> compilation if the compiler can't prove that a condition is true.
>
>
But it makes some code impossible to write:

#define compiler_assert(e) do \
        { \
                [[gnu::error("")]] extern void fail_(void); \
                                                                      \
                if (!(e)) \
                        fail_(); \
        } while (0)

void f(int* p) {
  compiler_assert(p != nullptr);
}

Even with optimizations turned up to maximum, this will always be
ill-formed.

The condition of "known at compile time" is weaker than the standard's
concept of "constant expression", but not formally specified and probably
impossible to specify in the abstract machine.

I've experimented with this kind of use of [[gnu::error]] for assertions in
libstdc++, and it's not usable in general, because most code cannot require
that all inputs are compile-time constants.

Received on 2026-02-19 15:33:41