Search code examples
c++stringmacrosstring-literals

Passing the string value instead of const string literal to macro with stringizing operator


I want to pass string value into some macro called TEST_FAIL. I tried following code

string error = "myError";
TEST_FAIL(error.c_str());
TEST_FAIL("myError");

but the output of this is

error.c_str()
"myError"

How can I get in the first line value of string error, i.e "myError" in both lines?

I use macro from the library which is define like this

#define TEST_FAIL(msg) \
{                                                               \
    assertment(::Test::Source(__FILE__, __LINE__, (msg) != 0 ? #msg : "")); \
    if (!continue_after_failure()) return;                      \
}

Solution

  • Inside the macro, the # before #msg is a macro extension that 'stringify' the expression (i.e., convert the exact expression into string. See here for more information).

    If you want to have the value of msg, just remove the # as following:

    #define TEST_FAIL(msg) \
    {                                                               \
        assertment(::Test::Source(__FILE__, __LINE__, (msg) != 0 ? msg : "")); \
        if (!continue_after_failure()) return;                      \
    }