how to use the constant variable's name as variable?

Z

zl2k

hi, there,

Well, the subject looks fuzzy but here is what I want to do but don't
know how.

Suppose I have

const int John = 123456789;
const int Bill = 111222333;
....

now I have a function

void function(string s){
// s is of "John" or "Bill" or ... and I want to print the number
associated with the name.
// however, I don't want to do if else
}

Thanks a lot.

zl2k
 
I

Ian Collins

hi, there,

Well, the subject looks fuzzy but here is what I want to do but don't
know how.

Suppose I have

const int John = 123456789;
const int Bill = 111222333;
....

now I have a function

void function(string s){
// s is of "John" or "Bill" or ... and I want to print the number
associated with the name.
// however, I don't want to do if else
}

You'll have to store the name somewhere and look it up. C++ doesn't do
reflection.
 
S

Saeed Amrollahi

hi, there,

Well, the subject looks fuzzy but here is what I want to do but don't
know how.

Suppose I have

const int John = 123456789;
const int Bill = 111222333;
...

now I have a function

void function(string s){
   // s is of "John" or "Bill" or ... and I want to print the number
associated with the name.
   // however, I don't want to do if else

}

Thanks a lot.

zl2k

The name of variables are source code entities, not compile-time or
run-time things.
You can use something like that:
map<std::string, int> m;
m["John"] = 123456789;
m["Bill"] = 111222333;
or with C++0x:
map<std::string, int> m = { {"John", 123456789}, {"Bill",
111222333} };

Regards,
-- Saeed Amrollahi
 
Z

zl2k

hi, there,
Well, the subject looks fuzzy but here is what I want to do but don't
know how.
Suppose I have
const int John = 123456789;
const int Bill = 111222333;
...
now I have a function
void function(string s){
   // s is of "John" or "Bill" or ... and I want to print the number
associated with the name.
   // however, I don't want to do if else

Thanks a lot.

The name of variables are source code entities, not compile-time or
run-time things.
You can use something like that:
  map<std::string, int> m;
  m["John"] = 123456789;
  m["Bill"] = 111222333;
or with C++0x:
  map<std::string, int> m = { {"John", 123456789}, {"Bill",
111222333} };

Regards,
  -- Saeed Amrollahi

Thanks, got that.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top