C Preprocessor, Stringify the result of a macro

风格不统一 提交于 2019-11-26 11:18:16

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.

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!