Originally Posted by
MortalMonkey
A challenge, just for fun:
Make a function that behaves exactly like a variable.
I love a good challenge so here goes (if this is a trick question though, I'll feel really dumb ):
A variable stores a value so all it seems we need is a function that mimics this, ie. returns an inputed value. My first idea was something very simple like this:
Code:
int imaVariable(int x)
{
return x;
}
But I can already see some problems with this too simple idea. A global variable (for example) would stay in scope for the whole duration of the program's running time. As long as you don't change it the value of the variable stays the same the whole time. This function, however, would have to be filled with a value every time you called it. Kinda defeats the purpose of using a variable to store stuff. We would need a function that would ask for a value once and then retain it so that when you call it again you don't have to pass it arguements.
My second idea was to make a function that takes no arguments but asks for input and returns that input:
Code:
int imaVariable(void)
{
int value;
cout<<"Enter value: "<<endl;
cin>>value;
return value;
}
But again, the same problem... every time you call the function, you have to input the value.
My last idea was to simply assign a value to the function:
Code:
int imaVariable(void)
{
return //value I want to assign the function goes here;
}
But this seems more like a constant than a variable to me so... I don't know...
Can such a function be created? At this point I don't know.
I've seen some amazing stuff on this board already so I won't be surprised if someone more experienced here can do it, but at this point in my study I don't think I can.
At any rate, thanks for the brain bender (well, brain bender for a noob like me). It's given me something to think about. Perhaps a function is like a temporary variable that does something.