Miles Chen
Miles Chen

Reputation: 793

How to accomplish this function in C/C++

I need a macro which helps to output the given parameter's name and value. It's something like the following code.

#define AA "Hello"
#define BB "World"
#define PRINT(input_param) printf("input_param: %s\n", (input_param))
void main()
{
  PRINT(AA);
  PRINT(BB);
}

I'm expecting the result: AA: Hello\n BB: World\n

But obviously it's not. Anybody can correct me? Thanks.

Upvotes: 7

Views: 182

Answers (1)

Ben Jackson
Ben Jackson

Reputation: 93710

You need to stringize the macro name with #. This is how assert() works as well:

#define AA "Hello"
#define BB "World"
#define PRINT(input_param) printf(#input_param ": %s\n", (input_param))
void main()
{
  PRINT(AA);
  PRINT(BB);
}

It may be more clear if I wrote it like this:

#define PRINT(input_param) printf("%s: %s\n", #input_param, (input_param))

Upvotes: 12

Related Questions