Aug 23, 2016

C Programming #82: stringification operator

C Programming #82: stringification operator

Following article explores stringification operator used in C Programming. It is used along with Macros in C. Sometimes it is needed to stringify the Macro parameter in such case following operator can be used.


# is the stringify operator, don't confuse this with # of the preprocessor directive (e.g #include, #define…). This operator is used in the third part of any Macro. Lets see one example.

#define SIMPLE_STRING(x) #x

Following Macro

SIMPLE_STRING(hello);

will be expanded as

"hello";

Lets see one classic example where it could be used.

#include <stdio.h>
#define COLOR_STR(x) "color "#x
char color[3][25] = { COLOR_STR(red), COLOR_STR(green), COLOR_STR(blue) };
int main()
{
   int i = 0;
   for(i = 0; i < 3; i++) {
      printf("%s\n", color[i]);
   }
   return 0;
}
color red
color green
color blue

There is more elegant usage of it called X-macro which will be covered later.

No comments :

Post a Comment