A function can call an another function.
A lambda function can use the variables of surrounding (function) scope.
A function can return value and pass parameters by reference.
I have a program I am supposed to write for school where you use a structure to set the variables and etc. then u create a function to get the data then you create a function to output the data. I cant for the life of me figure out how to use the DATA from the function i collect data into the function I want to use to output the collected data. It is eluding me badly
But what ur saying is that u get the data into the function, but u dont know how to give that data to the output function?
Well functions have a return type and parameters, let me show u something
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
string DATA(string &s)
{
// do some stuff with s
return s; // return the string
}
void output(const string &s) // void returns nothing
{
cout << s << endl;
}
int main ()
{
string myDATA = "Hi";
output(DATA(myDATA)); // calls the DATA function and then uses the string returned by that and calls output
return 0;
}
Please excuse any errors above, as I wrote this from my ipad
If u dont know srrings then replace every string to a int
Do not do what @Jaybob66 said, it is bad practice. You should avoid global variables.
You can google search and 90% of the people will tell u that they are bad, the other 10% are beginners like me and u and dont know yet.
So yea dont use them, instead us parameters and return types.
I wasn''t suggesting that the data should be global, i suggested moving it so that it was in scope for both functions. What scope that is depends on the structure of the OP's code.
@Jaybob66: The way you wrote it, it seems like suggesting a use of global. Lets assume that Murphy's Law has full effect.
In essence the Xp3rtHamm0r's example has the data outside, but seen via parameters. However, that function DATA() has an extra complication:
It does return a (copy of) value that it got as reference parameter.
1 2 3 4 5 6 7 8
// This is same
string s, t;
t = DATA( s );
// as this
string s, t;
DATA( s );
t = s;
While the more the merrier, the KISS principle has clear merit.
Encapsulation is a useful keyword. It can make Jaybob66's code safe and sound:
string &DATA(string &s)
{
// do some stuff with s
return s; // return the string
}
void output(const string &s) // void returns nothing
{
cout << s << endl;
}
int main ()
{
string myDATA = "Hi";
output(DATA(myDATA)); // calls the DATA function and then uses the string returned by that and calls output
return 0;
}
// a function that returns a new value
string foo()
{
string s;
// do some stuff with s
return s;
}
// a function that changes an existing value
void bar( string & s )
{
// do some stuff with s
}