Constexpr constants inside a constexpr function?

Viewed 71

Suppose I have a static function which takes an enum and returns a cstring ptr for debugging.

The function can be constexpr but no guarantee is made that it can always be evaluated at compile time. Say it is running on a microcontroller and this is signalling events from a Bluetooth stack; e.g. device connected, disconnected, data in, etc, for context. So the parameter is not necessarily known at compile time.

Is there any value, meaning or difference in having the cstrings also defined as constexpr vs not?

A condensed example of what I mean:

#include <cstdio>

enum myEnum
{
    EVENT1,
    EVENT2,
    EVENT3
};

static constexpr const char* foo(const myEnum i)
{
    // Does having these as constexpr change anything?
    /*constexpr*/ const char* text1 = "Text1";
    /*constexpr*/ const char* text2 = "Text2";
    /*constexpr*/ const char* text3 = "Text3";
    /*constexpr*/ const char* textUndef = "TextUndef";

    switch (i)
    {
    case EVENT1:
        return text1;
    case EVENT2:
        return text2;
    case EVENT3:
        return text3;
    default:
        return textUndef;
    }
}

int main()
{
    const char* x = foo(EVENT1);
    const char* y = foo(/*some value only known at runtime*/);

    printf(x);
    printf(y);

    return 1;
}

I am compiling with gcc for cpp17 for an embedded microcontroller. Typically with either -Og or -Os.

1 Answers

Having the variables const char* declared constexpr in foo() doesn't add any value because you're not exploiting their constexpr-ness inside the function.

In main, you could declare x as constexpr in order to be sure that x's value is assigned at compile time. This could be useful because calling a constexpr function (even when passing literal values) doesn't guarantee that it will be evaluated at compile time. There's a catch though: you will not be able to modify the pointer anymore (x will become a const char *const, that is a const pointer to const char).

y is always evaluated at run time, so you cannot declare it constexpr.

My suggestion is to try your snippets in godbolt.org so that you can see the results with different optimizations options

Related