returning a variable's name as a string

May 23, 2009 at 6:10pm
closed account (oG8U7k9E)
Is there a function or a way to write a function that will return the name of a variable as a string?

What I want is to create a function which when given the name of an integer would print both the name of the parameter as a string and the value of that parameter to my terminal.

It seems easy but I cannot figure out to do it.
May 23, 2009 at 6:40pm
Variable names are simply for your conveinience. They do not (or rather, may not) exist in the final executable.

So no, what you're wanting to do is not possible in C++*. If you want to print a string, you need to keep track of a string as a variable.


*it may technically be possible if you exploit the generated debugging symbols produced by the compiler -- so if you want to be hypertechnical it's possible, but not practical


EDIT:

There are ways to work around this. For instance rather than using just an int, use a struct/class that has both an int and a string. So you can manipulate the int and print the string.
Last edited on May 23, 2009 at 6:42pm
May 23, 2009 at 6:45pm
You could use a macro. I would only suggest this for debugging purposes, though:
1
2
3
4
#define SHOW(a) std::cout << #a << ": " << (a) << std::endl
// ...
int i = 2;
SHOW (i);

May 23, 2009 at 6:57pm
Hey, I like that macro. If you don't mind, I'm going to improve it just a little:
#define TO_STREAM(stream,variable) (stream) <<#variable": "<<(variable)

EDIT: It really is a shame that C++ doesn't have any reflective support.
Last edited on May 23, 2009 at 6:58pm
May 23, 2009 at 7:21pm
Oh hey that's something I hadn't thought of! Probably because I like never use macros XD

Nifty.
May 23, 2009 at 7:41pm
closed account (oG8U7k9E)
Hammurabi,

I am using it for debugging and It works like a dream. Thank you so much.
May 23, 2009 at 7:51pm
Here's an interesting (?) variation:

1
2
3
4
5
6
7
8
9
#include <iostream>

#define _(x) std::cout << #x << std::endl; x

int main() {
    _(int i = 0;)
    _(i = 1;)
    _(std::cout << i;)
}
Topic archived. No new replies allowed.