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...
This is great for meta programming.
ReplyDeleteI 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:
ReplyDeleteint main() {
int var = 100; // just any type of identifier
puts("var");
return 0;
}
It was fun when I was a noob in C. Now I am a pro :P
DeleteZobayer hasan : (y)
ReplyDeletehi, how can i doing this in c sharp?
ReplyDeletehi, how can i doing this for c sharp code?
ReplyDeleteuse this way,
ReplyDelete#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!!!