How to print and store a variable name in string variable?
We strongly recommend you to minimize your browser and try this yourself first
In C, there’s a # directive, also called ‘Stringizing Operator’, which does this magic. Basically # directive converts its argument in a string.
#include <stdio.h>
#define getName(var) #var
int main()
{
int myVar;
printf ( "%s" , getName(myVar));
return 0;
}
|
We can also store variable name in a string using sprintf() in C.
# include <stdio.h>
# define getName(var, str) sprintf(str, "%s", #var)
int main()
{
int myVar;
char str[20];
getName(myVar, str);
printf ( "%s" , str);
return 0;
}
|
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
28 Jun, 2021
Like Article
Save Article