Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stringification of a macro value

I faced a problem - I need to use a macro value both as string and as integer.

 #define RECORDS_PER_PAGE 10   /*... */   #define REQUEST_RECORDS \       "SELECT Fields FROM Table WHERE Conditions" \       " OFFSET %d * " #RECORDS_PER_PAGE \       " LIMIT " #RECORDS_PER_PAGE ";"   char result_buffer[RECORDS_PER_PAGE][MAX_RECORD_LEN];   /* ...and some more uses of RECORDS_PER_PAGE, elsewhere... */ 

This fails with a message about "stray #", and even if it worked, I guess I'd get the macro names stringified, not the values. Of course I can feed the values to the final method ( "LIMIT %d ", page*RECORDS_PER_PAGE ) but it's neither pretty nor efficient. It's times like this when I wish the preprocessor didn't treat strings in a special way and would process their content just like normal code. For now, I cludged it with #define RECORDS_PER_PAGE_TXT "10" but understandably, I'm not happy about it.

How to get it right?

like image 446
SF. Avatar asked Apr 16 '10 13:04

SF.


People also ask

How do I find the value of a macro?

There is no way you can test whether a defined macro has a value. You can only test whether a specific value matches the value of a macro. Any macro name that you define should always have a value, or it should never have a value.

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 does the '#' symbol do in macro expansion?

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.

How do you define macro parameters?

To define a macro that uses arguments, you insert parameters between the pair of parentheses in the macro definition that make the macro function-like. The parameters must be valid C identifiers, separated by commas and optionally whitespace.


1 Answers

The xstr macro defined below will stringify after doing macro-expansion.

#define xstr(a) str(a) #define str(a) #a  #define RECORDS_PER_PAGE 10  #define REQUEST_RECORDS \     "SELECT Fields FROM Table WHERE Conditions" \     " OFFSET %d * " xstr(RECORDS_PER_PAGE) \     " LIMIT " xstr(RECORDS_PER_PAGE) ";" 
like image 126
Matthew T. Staebler Avatar answered Oct 14 '22 04:10

Matthew T. Staebler