How to print variable name in C ++?

Possible duplicate:
Programmatic way to get variable name in C?

I checked some blogs before posting it here. I tried the following snippet ...

int a=21; int main() { cout<<#a<<a<<endl; return 0; } 

I am using the g ++ compiler on ubuntu 10.04. And I get the following error:

 sample.cpp:17: error: stray '#' in program. 

Please suggest me how to print the name of variables.

+6
source share
2 answers

Macro line # only works inside macros.

You can 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; } 
+14
source

# is if you are writing a macro.

If your cout line was a macro, it will work as you expect.

If you are not in a macro, just enter "a" .

0
source

Source: https://habr.com/ru/post/909345/


All Articles