converting a variable name to a string in C++
Solution 1:
You can use the preprocessor "stringify" #
to do what you want:
#include <stdio.h>
#define PRINTER(name) printer(#name, (name))
void printer(char *name, int value) {
printf("name: %s\tvalue: %d\n", name, value);
}
int main (int argc, char* argv[]) {
int foo = 0;
int bar = 1;
PRINTER(foo);
PRINTER(bar);
return 0;
}
name: foo value: 0
name: bar value: 1
(Sorry for printf
, I never got the hang of <iostream>
. But this should be enough.)
Solution 2:
try this:
#define GET_VARIABLE_NAME(Variable) (#Variable)
//in functions
int var=0;
char* var_name= GET_VARIABLE_NAME(var);