Programmatic way to get variable name in C?

Viewed 45777

I am developing a tool to dump data from variables. I need to dump the variable name, and also the values.

My solution: Store variable name as a string, and print the "variable name", followed by its value.

Is there any programmatic way to know the variable name?

10 Answers

Shorter way:

#define GET_VARIABLE_NAME(Variable) (#Variable)

test:

#include <string>
class MyClass {};


int main(int argc, char* argv[]) {
    int foo = 0;

    std::string var_name1 = GET_VARIABLE_NAME(foo);
     char* var_name2 = GET_VARIABLE_NAME(foo);
     char* var_name3 = GET_VARIABLE_NAME(MyClass);


    return 0;
}

Despite the very precise answer from @Matt Joiner, I wanna write a full short code exemplifying this just to see how simple it is using #define macro

#include <stdio.h>
#define val_name(v)#v
int main()
    {
    char a[]="hello";
    printf("%s %s",a,val_name(a));
    }

output: hello a

Related