110

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.

a3f
  • 8,517
  • 1
  • 41
  • 46
Ian
  • 4,169
  • 3
  • 37
  • 62

5 Answers5

183

Use the preprocessor # operator:

#define CALL_DO_SOMETHING(VAR) do_something(#VAR, VAR);
Morwenn
  • 21,684
  • 12
  • 93
  • 152
45

You want to use the stringizing operator:

#define STRING(s) #s

int main()
{
    const char * cstr = STRING(abc); //cstr == "abc"
}
chris
  • 60,560
  • 13
  • 143
  • 205
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";
Zili
  • 197
  • 1
  • 2
  • How does this answer the question or how is it helpful? – jirig Apr 02 '18 at 19:21
  • 2
    @jirigracik -- It allows to get string presentation of macro expansion as well, unlike other answers – grepcake Jun 15 '18 at 18:06
  • 10
    I think it would be useful to explain why having just `QUDI(x)` is not enough. – LRDPRDX Feb 06 '20 at 07:55
  • 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). – GMc Dec 02 '20 at 08:16
14
#define NAME(x) printf("Hello " #x);
main(){
    NAME(Ian)
}
//will print: Hello Ian
  • 1
    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 Jun 09 '17 at 13:37
  • 2
    @Smar Make sure you put a space after the constant string Hello: `"Hello " #x` – jack Jun 11 '17 at 00:37
  • Okay I thought so, you should edit that to your answer too since it’s valuable piece of information :) – Smar Jun 11 '17 at 06:00
  • #define NAME(x) printf("Hello %s", #x); – Liam de Koster-Kjaer Dec 01 '21 at 09:11
0
#define THE_LITERAL abcd

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

std::string abcd = TO_LITERAL(THE_LITERAL); // generates abcd = "abcd"
Audrius Meškauskas
  • 20,936
  • 12
  • 75
  • 93