How to use Macro argument as string literal?
Asked Answered
D

5

114

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.

Disastrous answered 8/5, 2012 at 22:7 Comment(1)
How are you trying to use this?Raman
A
192

Use the preprocessor # operator:

#define CALL_DO_SOMETHING(VAR) do_something(#VAR, VAR);
Auraaural answered 8/5, 2012 at 22:12 Comment(0)
R
45

You want to use the stringizing operator:

#define STRING(s) #s

int main()
{
    const char * cstr = STRING(abc); //cstr == "abc"
}
Raman answered 8/5, 2012 at 22:12 Comment(0)
A
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";
Alveolate answered 23/8, 2016 at 18:32 Comment(4)
How does this answer the question or how is it helpful?Burgh
@jirigracik -- It allows to get string presentation of macro expansion as well, unlike other answersPlyler
I think it would be useful to explain why having just QUDI(x) is not enough.Herbherbaceous
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).Cytherea
M
14
#define NAME(x) printf("Hello " #x);
main(){
    NAME(Ian)
}
//will print: Hello Ian
Melissa answered 1/10, 2014 at 22:31 Comment(4)
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.Eboh
@Eboh Make sure you put a space after the constant string Hello: "Hello " #xAdministrator
Okay I thought so, you should edit that to your answer too since it’s valuable piece of information :)Eboh
#define NAME(x) printf("Hello %s", #x);Gailgaile
O
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"
Overmantel answered 27/3, 2023 at 10:51 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.