Before going to write C program for this problem, I would like to tell about the stringizing operator in C?
The operator # is known as the stringizing operator in C. The stringizing operator (#) converts, its argument in a string.
Method 1: Here is the C program to print variable name using a single line macro and stringizing operator.
/*
* Method 1 : To print variable name using single line MACRO
* and stringizing operator
*/
#include <stdio.h>
#define printVar(varName) #varName
int main ()
{
int acTestVar;
printf("%s\n", printVar(acTestVar));
return 0;
}
Method 2: Here is the C program to print variable name using a multiline macro and stringizing operator & storing variable name in strBuf using sprintf(), then printing it.
/*
* Method 2 : To print variable name using multiline MACROs
* stringizing operator & storing variable in strBuf using sprintf()
*/
#include <stdio.h>
#define printVar(varName,strBuf){\
sprintf(strBuf,"%s\n",#varName);\
printf("%s", strBuf);\
}
int main ()
{
int acTestVar;
char strBuf[32];
printVar(acTestVar, strBuf);
return 0;
}
Method 3: Here is the C program to print variable name using a single line macro and stringizing operator & storing variable name in strBuf using sprintf(), then printing it.
/*
* Method 3 : To print variable name using single MACROs
* stringizing operator & storing variable in strBuf using sprintf()
*/
#include <stdio.h>
#define printVar(varName,strBuf) sprintf(strBuf,"%s\n",#varName)
int main()
{
int acTestVar;
char strBuf[32];
printVar(acTestVar, strBuf);
printf("%s", strBuf);
return 0;
}
Hope, it would be helpful .
To contribute :
” If you like Advance Computing and would like to contribute, you can mail your article to “computingadvance@gmail.com”. You will get credit as your name , email id, designation with article on this blog. “