Re: creating a custom named variable with a function
Hi,
Justcallmedrago@yahoo.com wrote:
How would you declare and assign a variable inside a function?
*the variable must end up having the name as the parameter
*i don't want to declare the variable before i call the function.
You cannot do this the direct way.
example:
when you call createvariable("eggroll")
it will declare the variable "eggroll"
and then maybe assign it something.
eggroll = "this is a real variable"
also so you can use it later, outside of the function.
You cannot make it a variable in the C++ sense of this word, but you can
use some global dictionary (a map to be precise) which will serve the
same purpose:
std::map<std::string, std::string> myVariables;
and then:
void createVariable(const std::string &varName)
{
myVariables[varName] = "this is a real variable";
}
so that after calling:
createVariable("eggroll");
you can read (use) it, for example:
std::cout << myVariables["eggroll"];
If you like this idea, you will also like boost::any.
--
Maciej Sobczak : http://www.msobczak.com/
Programming : http://www.msobczak.com/prog/
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]