Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to accomplish this function in C/C++

Tags:

c++

c

macros

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.

like image 330
Miles Chen Avatar asked Jun 23 '12 02:06

Miles Chen


1 Answers

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))
like image 168
Ben Jackson Avatar answered Oct 12 '22 05:10

Ben Jackson