0

I want to check if a constexpr number is in a constexpr array at compile time. If not, stop compiling. My ideographic example:

constexpr void PinValid(uint8_t Pin)
{
    constexpr uint8_t ValidPins[] = {2, 3, 18, 19, 20, 21};
    for (uint8_t P : ValidPins)
        if (Pin == P)
            return;
    static_assert(false);
}

This code fails for any given Pin even if it is in the ValidPins.

2
  • 3
    static_assert(false) will always fail at compile time. Commented Sep 30, 2022 at 2:57
  • @ChuckWalbourn So how to do this check? Commented Sep 30, 2022 at 3:25

2 Answers 2

3

You can write like this:

constexpr bool PinValid(uint8_t Pin)
{
    constexpr uint8_t ValidPins[] = {2, 3, 18, 19, 20, 21};
    for (uint8_t P : ValidPins)
        if (Pin == P)
            return true;
    return false;
}

static_assert(PinValid(3));
Sign up to request clarification or add additional context in comments.

2 Comments

Cool. I thought constexpr functions cannot have more than one returns. But your code did passed compilation. So what is it that is limited to have only one return statement?
I think 'constexpr' means the func returns a same result for a same input. It can have various results. constexpr specifier
0

I'd like to add the following solution, even if the quality of the error message isn't as good as in the example in the other answer, on some compilers.

In c++20 you can throw an exception in a constexpr function which will result in a compilation error if it gets thrown at compile-time:

#include <cstdint>
#include <array>
#include <stdexcept>


consteval void PinValid(uint8_t Pin)
{
    constexpr uint8_t ValidPins[] = {2, 3, 18, 19, 20, 21};
    for (uint8_t P : ValidPins)
        if (Pin == P)
            return;
    throw std::invalid_argument("not a valid pin");
}

int main() {
    PinValid(20);
    PinValid(5); // Does not compile
}

See the example on Compiler Explorer. Notice that it currently doesn't work on clang, though

1 Comment

Thanks. Unfortunately my compiler has not implemented C++20 yet, as indicated in the question's tags.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.