Possible Duplicate:
Programmatic way to get variable name in C?
I have checked some of the blogs before posting this here. I have tried the following snippet...
int a=21;
int main()
{
cout<<#a<<a<<endl;
return 0;
}
I am using g++ compiler on ubuntu 10.04. And I am getting the following error:
sample.cpp:17: error: stray ‘#’ in program.
Please suggest me how to print the variables 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. We can also store variable name in a string using sprintf() in C.
To print a variable's name: Use the globals() function to get a dictionary that implements the current module namespace. Iterate over the dictionary to get the matching variable's name. Use the print() function to print the variable's name.
Variable names in C are made up of letters (upper and lower case) and digits. The underscore character ("_") is also permitted. Names must not begin with a digit. Unlike some languages (such as Perl and some BASIC dialects), C does not use any special prefix characters on variable names.
disp( X ) displays the value of variable X without printing the variable name. Another way to display a variable is to type its name, which displays a leading “ X = ” before the value.
The #
stringifying macro thing only works inside macros.
You could do something like this:
#include <iostream>
#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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With