C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Allow assert in constexpr functions

From: Jonathan Wakely <cxx_at_[hidden]>
Date: Wed, 26 Mar 2025 14:51:37 +0000
On Wed, 26 Mar 2025 at 14:40, Frederick Virchanza Gotham via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> Today my compiler gave me the following output:
>
> md5.hpp:244:21: error: call to non-‘constexpr’ function ‘void
> __assert_fail(const char*, const char*, unsigned int, const char*)’
> 244 | assert( 0u == (*ptr >> 8u) );
>
>
> We should be able to use 'assert' in a constexpr function.


You can.


> If the
> function is invoked at compile time (instead of runtime), then it
> should be as if the 'assert' was never there. This would be the
> easiest way of doing it.
>

I don't see why we'd want that.


>
> A more complicated way of doing it would be to get the compiler at
> compile time to actually evaluate the assertion, and to cease
> compiling if the assertion fails -- this would be ideal.
>

Isn't that exactly what happened in this case?

assert is already allowed in constexpr functions, there's only a problem if
the assertion fails. If that happens, it tries to call a non-constexpr
function and you get an error.

Received on 2025-03-26 14:51:55