Convert any variable to string in C

hakuna matata picture hakuna matata · Jun 19, 2013 · Viewed 10.1k times · Source

Is is possible to convert any variable of any type to string?

I wrote the following

#define TO_STRING(val) #val

Is this a valid way of converting a variable into a string?

Answer

unwind picture unwind · Jun 19, 2013

You will get a string version of the variable's name, i.e. it will convert a to "a". The #when used like this is called the stringification operator.

For example:

#define TO_STRING(val) #val

int main(void)
{
  const int a = 12;
  print("a is %s\n", TO_STRING(a));
  return 0;
}

This will print a is a.

What do you expect to happen?

You can't get the variable's value, of course, since that's not available when the pre-processor runs (which is at compile-time).