2

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.

  • offtopic: FYI [this might be fun to use](https://github.com/Neargye/magic_enum). – Marek R Jan 15 '21 at 11:25
  • Does look fun yeah. A lot of std lib stuff though so I wouldn't use it for deployable code. – GreenaGiant Jan 15 '21 at 11:30
  • The other problem is that is uses compiler-specific hacks to do its reflection, which is impressive as an exercise but not something I'd want to depend upon in anything prod. – underscore_d Jan 15 '21 at 11:42

1 Answers1

1

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

Mario Demontis
  • 469
  • 3
  • 11
  • Thanks. Is there anything inherently wrong with the variables in foo() being declared constexpr? Apart from that possibly being confusing/misleading? Noted about the ptr being const, that's fine actually. Thanks – GreenaGiant Jan 15 '21 at 12:27
  • 1
    @GreenaGiant I don't see it wrong. Just useless – Mario Demontis Jan 15 '21 at 14:36