C++ Logo

std-proposals

Advanced search

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

From: Jonathan Grant <jg_at_[hidden]>
Date: Thu, 5 Mar 2026 00:46:03 +0000
On 20/02/2026 14:52, Sebastian Wittmeier via Std-Proposals wrote:
> AW: [std-proposals] compile_assert() a static assert that fires at compile time, not runtime.
>
> It is useful. It would make some code safe without any exception or abort (at least not for that reason):
>
>
>
> T& operator[](int index)
>
> static_pre(index > 0 && index < N) // variant 1
>
>
>
> {
>
> compile_assert(index > 0 && index < N); // variant 2
>
> return backingstore[index];
>
> }
>
>
>
> Now the user has to do explicit error checking beforehand or implicitly ensure that the precondition is met.
>
>
>
> // E.g.
>
> if (a < 0 || a >= N)
>
> error_handling(); // does not return
>
> int a = arr[n];
>
>
>
> if the if-check is removed and another proof is not (easily) possible, the program won't compile
>
>
This is exactly the use-case! Forces programmer to do pre-checks before the compile_assert() Catches uncompressing variable sized data into a fixed sized buffer errors. (I'd rather my compressed image failed to decode and showed ERR than over run memory)

Thank you again for looking into it Sebastian.

If you have any more feedback I'd be happy to read.
Latest revision is here
https://isocpp.org/files/papers/P4021R1.pdf

Regards, Jonathan


>
>
> -----Ursprüngliche Nachricht-----
> *Von:* Jan Schultke <janschultke_at_[hidden]>
> *Gesendet:* Fr 20.02.2026 15:52
> *Betreff:* Re: [std-proposals] compile_assert() a static assert that fires at compile time, not runtime.
> *An:* std-proposals_at_[hidden];
> *CC:* Sebastian Wittmeier <wittmeier_at_[hidden]>;
>
>
> Can this feature proposal be lifted from a best-effort base to be reproducible?
>
> Something like preconditions contracts, which have to be provably be true at compile-time.
>
> Can there be hints to guide the compiler to a deterministic proof?
>
>
> We could at least specify that if the condition is a constant expression, the assertion behaves correctly instead of being best-effort. Anything past that would seemingly require us to standardize a bunch of control flow and data flow analysis, and I don't think anyone wants to do that just for the sake of this assertion.
>
> I think the target audience for this feature is aware that it's playing Russian Roulette with compiler errors, and should probably never be used in large production code bases that compile with more than one compiler, or at least not with default build flags. Making the feature even slightly more predictable comes with great effort, and I don't think it would meaningfully impact who would or wouldn't use the feature.
>
>

Received on 2026-03-05 00:46:10