C Preprocessor, Stringify macro result

I want to smooth out the result of a macro extension.

I tried the following:

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

And TESTE expands to: "TEST" while I'm trying to get "thisisatest". I know that this is the correct preprocessor behavior, but can someone help me in order to achieve another?

 Using TESTE #TEST is not valid Using TESTE QUOTE(thisisatest) is not what I'm trying to do 
+39
c-preprocessor stringification
Aug 05 '10 at 21:30
source share
2 answers

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 you replace macros in the macro body, they expand if they do not appear with the # or ## preprocessor statements in this macro. So str (with the TEST value in your code) does not expand in QUOTE , but expands in EXPAND_AND_QUOTE .

+68
Aug 05 '10 at 21:37
source share

To clarify a little more, essentially the preprocessor was executed to perform another "stage". ie:

1st case:

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

Second 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 
+13
May 11 '11 at 14:18
source share



All Articles