top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to print a variable name in C?

+1 vote
892 views
How to print a variable name in C?
posted Jul 18, 2017 by Ajay Kumar

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+1 vote
 
Best answer

Use # directive which can do the magic, see the following program -

#include <stdio.h>
#define getVarName(x)  #x

main()
{
    int queryhome;
    printf("%s", getVarName(queryhome));
} 
answer Jul 19, 2017 by Salil Agrawal
Nice one sir....
Thanks sir
+1 vote

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

2)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
answer Jul 19, 2017 by Vipin
...