118

I am trying to figure out how to write a macro that will pass both a string literal representation of a variable name along with the variable itself into a function.

For example given the following function.

void do_something(string name, int val)
{
   cout << name << ": " << val << endl;
}

I would want to write a macro so I can do this:

int my_val = 5;
CALL_DO_SOMETHING(my_val);

Which would print out: my_val: 5

I tried doing the following:

#define CALL_DO_SOMETHING(VAR) do_something("VAR", VAR);

However, as you might guess, the VAR inside the quotes doesn't get replaced, but is just passed as the string literal "VAR". So I would like to know if there is a way to have the macro argument get turned into a string literal itself.

1
  • How are you trying to use this? Commented May 8, 2012 at 22:21

5 Answers 5

197

Use the preprocessor # operator:

#define CALL_DO_SOMETHING(VAR) do_something(#VAR, VAR);
Sign up to request clarification or add additional context in comments.

Comments

49

You want to use the stringizing operator:

#define STRING(s) #s

int main()
{
    const char * cstr = STRING(abc); //cstr == "abc"
}

Comments

15
#define NAME(x) printf("Hello " #x);
main(){
    NAME(Ian)
}
//will print: Hello Ian

4 Comments

I’m not totally sure, but it looks like "Hello" #x" (and #x "Hello") causes the string to be glued together without space, which is what is desired in some cases, so this is fairly good answer.
@Smar Make sure you put a space after the constant string Hello: "Hello " #x
Okay I thought so, you should edit that to your answer too since it’s valuable piece of information :)
#define NAME(x) printf("Hello %s", #x);
15

Perhaps you try this solution:

#define QUANTIDISCHI 6
#define QUDI(x) #x
#define QUdi(x) QUDI(x)
. . . 
. . .
unsigned char TheNumber[] = "QUANTIDISCHI = " QUdi(QUANTIDISCHI) "\n";

4 Comments

How does this answer the question or how is it helpful?
@jirigracik -- It allows to get string presentation of macro expansion as well, unlike other answers
I think it would be useful to explain why having just QUDI(x) is not enough.
This is exactly what I was looking for. The explanation as to why it works would be useful, but it solved my problem (which the other answers did not).
1
#define THE_LITERAL abcd

#define VALUE(string) #string
#define TO_LITERAL(string) VALUE(string)

std::string abcd = TO_LITERAL(THE_LITERAL); // generates abcd = "abcd"

2 Comments

Would be nice to get some explanation why we need a two step approach here... not clear to me. But your solution seems to be the only one which works for me :-)
@Klaus, it's to first expand the macro arguments. See here: stackoverflow.com/questions/16989730/… I agree though, this answer could be better explained.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.