Friday, May 28, 2010

C++ :: Get Variable's Name



How to print a variables name instead of its value? (not just by giving the name yourself)

This can be easily done with a #define pre-processor directive. As #define treats the preceding expression as cstring, it is possible to get the variables name as a string. Look below:

#include <stdio.h>

#define getVarName(varName,holder) sprintf(holder, "%s", #varName)

int main() {
int var = 100; // just any type of identifier
char name[100]; // it will get the variables name
getVarName(var, name);
puts(name);
return 0;
}

It will print "var" instead of "100" or something other. I saw it years ago somewhere I can't remember now. Today, it suddenly struck me and I think it might be useful who knows when...

7 comments:

  1. This is great for meta programming.

    ReplyDelete
  2. I don't think the getVarName is doing much here. It just prints out whatever you type in for the first argument. Since you know to type in "var" (without the quotes), it is easier to just do it as below:

    int main() {
    int var = 100; // just any type of identifier
    puts("var");
    return 0;
    }

    ReplyDelete
    Replies
    1. It was fun when I was a noob in C. Now I am a pro :P

      Delete
  3. hi, how can i doing this in c sharp?

    ReplyDelete
  4. hi, how can i doing this for c sharp code?

    ReplyDelete
  5. use this way,

    #include

    #define VNAME(x) #x
    #define VDUMP(x) std::cout << #x << " " << x << std::endl

    int main()
    {
    int i = 0;
    std::cout << VNAME(i) << " " << i << std::endl;

    VDUMP(i);

    return 0;
    }

    Example from stackoverflow.
    permalink: http://stackoverflow.com/a/9445004/2363074

    Thank you!!!

    ReplyDelete