1

I'm trying to make a function in C++ that can make a new integer type variable according to the name that has been provided

for eg

void my_variable(char name)
{
    int "something here" = 1;  // i am figuring out what to write 
    // there so that it makes a variable from that character that i have sent

    cout << "something here";
}
5
  • 3
    Local variable names only exist at compile time, so such a feature would have no use. Perhaps you can explain your high-level goal? Commented Jun 11, 2012 at 20:48
  • Wrong language for this, you have picked. Commented Jun 11, 2012 at 20:48
  • preprocessor can do this with ## to join strings into whatever. Commented Jun 11, 2012 at 20:50
  • Maybe you like to define a class MyInt with a 'name' attribute in it? Commented Jun 11, 2012 at 20:50
  • well im sort of new to the language.. u know , still using the Borland Turbo C++.. I was kinda hoping that i could assign variables like these, in a game Commented Jun 11, 2012 at 20:53

2 Answers 2

4

Look at using std::map. It allows you to create key-value pairs. The key would be name in this instance and the value would be the int. The following snippet shows you how to make a map, populate it, and then search for a value based on a key . . .

void my_function(std::string name)
{
    std::map<std::string, int> myMap;
    myMap[name] = 1;  // 

    cout << "Key " << name << " holds " << paramMap.find(name)->second << std::endl;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Well, std::pair allows you to create key-value pairs. std::map allows you to look up pairs by the first half of their value.
std::pair allows you to create "first-second" pairs. The interpretation of pair::first as Key and pair::second as Value is specific to std::map.
1

Since no one posted it as an answer, sometimes it is convenient to define a macro to create a variable.

#define DEFINE_HELPER(x) Helper helper_##x = Helper(#x)
#define HELPER(x) (&helper_##x)

struct Helper {
    std::string name;
    Helper (const char *s) : name(s) {}
};

DEFINE_HELPER(A);
DEFINE_HELPER(B);

std::cout << HELPER(A)->name << std::endl;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.