How to compare an int variable name to a string?

So for example, I want to compare the name of an int variable to a string, and if the name of the variable is the same as the string, then do certain action.
1
2
3
4
5
6
7
8
  int r1 = 0; 

  string tester = "r1";

  if(r1 == tester){
        //do something...
  }


Is this possible?
this makes no sense. if tester is "r1" then it can't be "0"

but, to answer your quest, yes, you can do things like this.
first, you can do it 'legit'...
if(tester == "r1")
something

or
if(tester == "0" && othertester == "r1") //use two variables, one to indicate its r1 we care about?

and second, less legit, there is a macro tokenizer that can turn a variable into its name.
shamelessly stolen off the web this one helps print name / value pairs
#define PRINTER(name) printer(#name, (name))

so in your case I guess you can turn r1 into "r1" but that seems silly for the example: you can just type "r1" there.

this is something you can ONLY do with a macro, and its not really all that useful most of the time but its a great helper for an ENUM that needs to show the user the variable names.
Last edited on
I want to compare the name of an int variable

Seems unlikely. Variables don't have names once the compiler is done. The generated executable doesn't contain the names of variables.

What do you actually want to do? Tell us what you want to do, without using the idea of a variable's name.
an xy problem...
A somewhat roundabout way.
But you have to know in advance which vars you want to lookup by name.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <string>
#include <map>

int main()
{
    int r1 = 42;
    std::map<std::string,int*> whodat;
    whodat.insert(std::pair<std::string,int*>("r1",&r1));
    
    std::map<std::string,int*>::iterator it;
    std::string name = "r1";
    it = whodat.find(name);
    if (it != whodat.end()) {
        std::cout << "Your var=" << *it->second << std::endl;
    }
}


Topic archived. No new replies allowed.