7

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 .

Community
  • 1
  • 1
user1232611
  • 91
  • 1
  • 2
  • 6

2 Answers2

14

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;
}
Mat
  • 202,337
  • 40
  • 393
  • 406
  • 1
    @JamesMcLaughlin - But you can make the macro more complex. – Ed Heal Feb 25 '12 at 14:54
  • 3
    @JamesMcLaughlin that's not quite the same: if you rename your variable to `j` and forget to update the `"i"` string, there would be no compile-time error; using `VNAME` macro on a *variable* ensures that the printed value stays "synchronized" with the compile-time name of the variable. – Sergey Kalinichenko Feb 25 '12 at 14:56
  • 1
    @dasblinkenlight What if you renamed your variable to `j` and there was another variable called `i`? There'd be no compile time error, and it'd show the wrong name. The `VDUMP` macro that just got added is far better. – James M Feb 25 '12 at 17:50
  • @jamesmclaughlin VDUMP suffers from the same problem as VNAME: in case you rename i to j but there is another variable called i, you'd see a correct but useless output (assuming that you wanted to see j, not i), so it is still wrong. my point was that a variable name is visible to the compiler, but the content of a string constant is not. – Sergey Kalinichenko Feb 25 '12 at 18:06
  • @dasblinkenlight `VDUMP` provides safety that the variable you're printing matches the label. Printing the _wrong_ variable is a different problem entirely (and an unavoidable one). – James M Feb 25 '12 at 19:54
0

The # is for if you are writing a macro.

If your cout line were a macro, it would work the way you expect.

If you're not in a macro, you just type "a".

StilesCrisis
  • 15,972
  • 4
  • 39
  • 62