Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Preprocessor, Stringify the result of a macro

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
like image 393
Ale Morales Avatar asked Aug 05 '10 21:08

Ale Morales


People also ask

What is stringizing operator in C?

Stringizing operator (#) The number-sign or "stringizing" operator (#) converts macro parameters to string literals without expanding the parameter definition. It's used only with macros that take arguments.

What does ## mean in macro?

The double-number-sign or token-pasting operator (##), which is sometimes called the merging or combining operator, is used in both object-like and function-like macros. It permits separate tokens to be joined into a single token, and therefore, can't be the first or last token in the macro definition.

What is macro expansion in preprocessor?

Advertisements. When the program run and if the C preprocessor sees an instance of a macro within the program code, it will do the macro expansion. It replaces the macro template with the value of macro expansion. The #define directive is a good way of declaring constant compared to a constant or a variable value.


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 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.

like image 165
Steve Jessop Avatar answered Oct 13 '22 18:10

Steve Jessop


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
like image 17
pratikm Avatar answered Oct 13 '22 20:10

pratikm