Search code examples
cstringc-preprocessorstringification

Printing the variable identifier formed by the preprocessor


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)?


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.