C Preprocessor, Stringify the result of a macro
Asked Answered
F

2

52

I want to stringify the result of a macro expansion.

I've tried with the following:

#define QUOTE(str) #str
#define TEST thisisatest
#define TESTE QUOTE(TEST)

And TESTE gets expanded to: "TEST", while I'm trying to get "thisisatest". I know this is the correct behavior of the preprocessor but can anyone help me with a way to achieve the other one?

Using TESTE #TEST is not valid
Using TESTE QUOTE(thisisatest) is not what I'm trying to do
Fidget answered 5/8, 2010 at 21:30 Comment(1)
https://mcmap.net/q/196867/-macros-to-create-strings-in-cProvidenciaprovident
D
85

Like this:

#include <stdio.h>

#define QUOTE(str) #str
#define EXPAND_AND_QUOTE(str) QUOTE(str)
#define TEST thisisatest
#define TESTE EXPAND_AND_QUOTE(TEST)

int main() {
    printf(TESTE);
}

The reason is that when macro arguments are substituted into the macro body, they are expanded unless they appear with the # or ## preprocessor operators in that macro. So, str (with value TEST in your code) isn't expanded in QUOTE, but it is expanded in EXPAND_AND_QUOTE.

Drupe answered 5/8, 2010 at 21:37 Comment(1)
#define PE(BZL,YY) printf("ERROR - " #BZL ": result: 0x%08x!", YY); Doing:int variable1=1; PE(Test1,variable1); --> Results printing: ERROR - Test1: result: 0x1!Disadvantageous
M
18

To clarify a bit more, essentially the preprocessor was made to execute another "stage". i.e :

1st case:

->TESTE
->QUOTE(TEST) # preprocessor encounters QUOTE 
 # first so it expands it *without expanding its argument* 
 # as the '#' symbol is used
->TEST

2nd case:

->TESTE
->EXPAND_AND_QUOTE(TEST)
->QUOTE(thisisatest) 
  # after expanding EXPAND_AND_QUOTE
  # in the previous line
  # the preprocessor checked for more macros
  # to expand, it found TEST and expanded it
  # to 'thisisatest'
->thisisatest
Merrileemerrili answered 11/5, 2011 at 14:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.