Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to print a variable name in C?

  • Difficulty Level : Medium
  • Last Updated : 28 Jun, 2021

How to print and store a variable name in string variable?

We strongly recommend you to minimize your browser and try this yourself first

Take a step-up from those "Hello World" programs. Learn to implement data structures like Heap, Stacks, Linked List and many more! Check out our Data Structures in C course to start learning today.

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;
Output:



myVar


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;
Output:
myVar

This article is contributed by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!