C++ Logo

std-proposals

Advanced search

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

From: Alejandro Colomar <une+cxx_std-proposals_at_[hidden]>
Date: Sat, 7 Mar 2026 15:43:05 +0100
Hi Simon,

On 2026-03-07T07:24:54+0100, Simon Schröder via Std-Proposals wrote:
>
>
> > On Mar 5, 2026, at 2:04 AM, Jonathan Grant via Std-Proposals <std-proposals_at_[hidden]> wrote:
> >
> > I usually use for very straight-forward things, like array access index bounds checks, or nullptr.
>
> If this is the main application area, I really don’t see the advantage
> over contracts. In many cases the compiler can (could?) be able to
> prove that the contract is always fulfilled and eliminate the check
> when optimization is turned on. So, it works the same if it can be
> proven (no runtime performance overhead). Where contracts and
> compile_assert differ is in cases where it cannot be proven. Contracts
> will just leave the check in and compile_assert refuses to compile.
> Outside of embedded systems I expect programmers to prefer contracts:
> an occasional overhead doesn’t hurt too much and I’d rather have my
> software working with this little overhead than having to fight a
> checker.

You mean you prefer a run-time crash over a compile-time diagnostic?

You don't need a hard error. A diagnostic that one could turn off would
be enough for safety. I've written a proposal for C, and I've specified
it so that there's only a mandatory diagnostic, and then compilation may
continue, if you wish.


Have a lovely day!
Alex

> Standard library hardening has shown in large projects that usually the overhead of contracts is negligible.
>
> One advantage of contracts over your proposal are the pre and post conditions that are checked (or eliminated) on every call. This means that with contracts it is not up to the programmer to remember to sprinkle compile_assert everywhere. You might even remove a compile_assert because the compiler cannot prove it. In the context of memory safety this makes compile_assert a worse choice than contracts (for everyone who can pay the tiny overhead).
>
> On the other hand, this is a strong point to make compile_assert an option for contract enforcement. However, this means that we would need a way to skip proving to make our program compile. Maybe we can add an attribute [[no_contract_proof]] (I couldn’t quickly come up with a better name) to function calls where we don’t want a compile time check of the pre condition. Or we can have a contract_assume() that only makes assumptions for contract proving, but has no influence on optimizations like [[assume()]]. (Though the regular [[assume()]] can be used by contract proving as well.)
> --
> Std-Proposals mailing list
> Std-Proposals_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals

-- 
<https://www.alejandro-colomar.es>

Received on 2026-03-07 14:43:12