Search code examples
c++macrosc-preprocessorstring-concatenation

Macro string concatenation


I use macros to concatenate strings, such as:

#define STR1 "first"
#define STR2 "second"

#define STRCAT(A, B) A B

which having STRCAT(STR1 , STR2 ) produces "firstsecond".

Somewhere else I have strings associated to enums in this way:

enum class MyEnum
{
    Value1,
    Value2
}
const char* MyEnumString[] =
{
    "Value1String",
    "Value2String"
}

Now the following does not work:

STRCAT(STR1, MyEnumString[(int)MyEnum::Value1])

I was just wondering whether it possible to build a macro that concatenate a #defined string literal with a const char*? Otherwise, I guess I'll do without macro, e.g. in this way (but maybe you have a better way):

std::string s = std::string(STR1) + MyEnumString[(int)MyEnum::Value1];

Solution

  • The macro works only on string literals, i.e. sequence of characters enclosed in double quotes. The reason the macro works is that C++ standard treats adjacent string literals like a single string literal. In other words, there is no difference to the compiler if you write

    "Quick" "Brown" "Fox"
    

    or

    "QuickBrownFox"
    

    The concatenation is performed at compile time, before your program starts running.

    Concatenation of const char* variables needs to happen at runtime, because character pointers (or any other pointers, for that matter) do not exist until the runtime. That is why you cannot do it with your CONCAT macro. You can use std::string for concatenation, though - it is one of the easiest solutions to this problem.