Pointers

say I have the following

const int a1=0, b1=1, c1=2, d1=3, e1=4, f1=5, g1=6, h1=7;
string square;

how would I get get the values of a1, b1, c1, etc. when the square="a1" or "b1" or "c1"...

is there such a thing a s pointer to a variable (not to the address)?

Thanks.
Last edited on
From what I see, you would like to do something like:

1
2
3
4
5
6
7
8
9
if( square == "a1")
{
std::cout<<a1;
}
else if( square == "a2")
{
std::cout<<a2;
}
//... and so on 


Well, then there's this way. If you need to do it for some more sophisticated reasons and it's just an example, or you simply have a huge data, then check maps:
http://www.cplusplus.com/reference/map/map/
I know but I am more interested in pointer kind of thing...
I would have more than 60 conts and I do not want to write all of those.
There is no way to convert a string containing an identifier name to some kind of actual reference to the variable itself because C++ is not reflective. At runtime all the names you have given variables no longer exist, in essence.
@Zhuge - That is true. What I am trying to do is find a code that would let the compiler points to the var in whatever type of referencing it would do at runtime.
Last edited on
You could make an std::map of std::strings to your variables. Then you could reference the variable by the string you assigned to them.
@MatthewRock & firedraco I would have to study map. Thanks.
Although I agree that std::map is the better approach, there is another rather ugly option using the C macro facility.
http://www.cplusplus.com/doc/tutorial/preprocessor/

1
2
3
4
5
#define F(x)  if (square == #x)  { cout << x; }

F(a1);
F(a2);
// etc 
So it seems there are several ways to do. Let me see which would be faster to process at runtime...
Topic archived. No new replies allowed.