Can I store pointer to __PRETTY_FUNCTION__ for later use or do I need to copy the string immediately?

Viewed 84

What is the lifetime of the string __PRETTY_FUNCTION__ produces?

I know __func__ generates equivalent of static const char __func__[] = "function-name";, Thanks to that static, if I want to create a record of something that happened in the function somewhere for referencing later, I can just store the value of __func__ in a const char* field in the record and retrieve it whenever I want, long after I left the scope of the function.

Does __PRETTY_FUNCTION__ behave the same way, or does the string it generates behave as a local, temporary value? Say, will this work reliably, or can it fail, fname pointing to a location where the function name used to be, and I need to do make a buffer and do strncpy() or similar instead?

#include <stdio.h>
const char* fname = NULL;

void foo()
{
    fname = __PRETTY_FUNCTION__;
}

int main()
{
    foo();
    printf(fname);
    return 0;
}
1 Answers

All three constants, __func__, __FUNCTION__ and __PRETTY_FUNCTION__, behave the same way. The GCC Manual states:

GCC provides three magic constants that hold the name of the current function as a string. In C++11 and later modes, all three are treated as constant expressions and can be used in constexpr contexts.

Related