Question

How to retrieve the text expanded from a macro?

#include <stdio.h>

#define paste(front, back) front ## back

int main()
{
    int number1 = 23;
    int number2 = 64;

    printf("%d\n", paste(number, 2));


    return 0;
}

The output is: 64 because the macro is expanded as:

printf("%d\n", number2);

How can I print the identifier number2 as string by using the defined paste macro. I need to know how to create the output: number2: 64 by not writing directly "number2" I don't want this solution:

printf("number2: %d\n", paste(number, 2))

I want a dynamic solution. I try to concatenate by doing:

printf("%s: %d\n", paste(number, 2), paste(number, 2));

But it doesn't work because number2 returned by the paste macro is an the identifier an integer How can I retrieve as a text (string)?

Was it helpful?

Solution

Use the stringizing directive #:

#define stringize_impl(x) #x
#define stringize(x) stringize_impl(x)

printf("%s: %d\n", stringize(paste(number, 2)), paste(number, 2));

On a side note: why are you trying to do this? Surely there must be a better solution.

OTHER TIPS

If you're compiling with GCC you can call it with gcc -E filename.c to see the expansion of macros.

EDIT:

You can also use the stringize preprocessor operator # that effectively puts double-quotes around the right-hand symbol.

#include <stdio.h>

#define T(...) #__VA_ARGS__
#define paste(f, b) _paste(f, b)
#define _paste(front, back) front##back

int main()
{
    int n = 5;
    printf("macro expands to: '%s'\n", T(paste(number, 2), paste(number, 2)));
    printf("macro expands to: '%s'\n", T(paste(n, 2)));
    return 0;
}

This code hopefully answers the question.

You need to expand the macro one more time to expand the paste in the stringize. In other words, for the paste macro inside the stringize macro to expand, the preprocessor has to pass over the file one more time. That's why you pass it through another macro defined later in the file.

I'm not 100% sure of ALL the rules of the preprocessor, but this seems to hold pretty well. For every macro you want to expand inside another macro, you need to do some magic to force the preprocessor to pass over the file again :) There exist different ways of achieving this to my knowledge, but this is one.

EDIT2:

Edited the code. I am getting this output, is this what you want?

morten@laptop:/tmp$ ./a.out 
macro expands to: 'paste(number, 2), paste(number, 2)'
macro expands to: 'paste(n, 2)'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top