Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print a variable's name in C++? [duplicate]

Tags:

c++

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 .

like image 924
user1232611 Avatar asked Feb 25 '12 14:02

user1232611


People also ask

Can you print a variable name in C?

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.

How do you print a variable name instead of a value?

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.

What is variable name in C?

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.

How do you print variable names in Matlab?

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.


1 Answers

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;
}
like image 101
Mat Avatar answered Oct 24 '22 14:10

Mat