0

This is kind of a follow-up question to one of my old questions here. I found some code that goes like this:

#define TYPESUPPORT(T)              \
...                                 \
static const char* get_type_name()  \
{                                   \
    return #T;                      \
}                                   \
...

Where T is a variable type (e.g. int). #T is used to get the plaintext name of the macro input.

Is this safe to do? As in, how is #T allocated? Does it allocate a const char* or const char[] string literal, like in my first question, for each macro call or something?

11
  • 7
    The macro is irrelevant, the preprocessor converts it to a string literal and it's processed just as if you'd written return "int"; Commented Jan 4, 2018 at 20:14
  • 4
    @JesperJuhl when you have about 300 types you need this info (as well as 4 other functions) for, you use macros. Commented Jan 4, 2018 at 20:16
  • 3
    @JesperJuhl That is hardly a useful comment. Most metaprogramming stuff cannot be done without some macro infrastructure, for example. Commented Jan 4, 2018 at 20:16
  • 3
    @Angew To be fair, C++ provides lots of support for metaprogramming using templates and other introspection features, so there's less need for macros. Commented Jan 4, 2018 at 20:18
  • 3
    @JesperJuhl Macros are much less useful in C++ than in C. That doesn’t mean they are completely useless; they still are often the best tool for the job. Each new version of C++ makes that less common, but they are still necessary, and in particular they are necessary here without using compiler-specific functions like abi::__cxa_demangle. Commented Jan 4, 2018 at 20:19

1 Answer 1

7

Macros simply perform text-to-text translation. So after TYPESUPPORT(int) is expanded, the function will look like:

static const char* get_type_name()  
{                                   
    return "int";                      
} 

And just as explained in the linked question, string literals have static storage duration, so there's no problem with returning this pointer. The fact that it came from expansion of #T is irrelevant at this phase of compilation.

Sign up to request clarification or add additional context in comments.

Comments

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.