C Programming

Print a variable name

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

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


Recent Comments

Feedback

For any feedback,email us at feedback@geeksforgeeks.org

Report a Bug

For any report or bug,email us at support@geeksforgeeks.org