Pulkit ShaRma
Pulkit ShaRma

Reputation: 67

How to declare a variable using another variable?

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";
}

Upvotes: 1

Views: 657

Answers (2)

jxh
jxh

Reputation: 70372

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;

Upvotes: 1

learnvst
learnvst

Reputation: 16195

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;
}

Upvotes: 4

Related Questions