Return from function means that function will produce some result and export it to rest of the program so other parts of program can grab it and use it as input values.
In an example down below our function addNumbers() will have 2 mandatory integers as parameters. We are stating that while declaring function above main() part of our program.
Below main() part of the program, we have function definition where operations are stated. In this case it's just simple addition.
Once we have result as product of operation, then we are returning it to the rest of the program. Note, we are not doing anything more inside addNumbers(), just exporting it to outside world:
#include <iostream>
#include <cstdlib>
using namespace std;
int addNumbers(int x, int y);
int main() {
cout << "Result of add: " << addNumbers(5, 10) << endl;
return 0;
}
int addNumbers(int x, int y) {
int result = x + y;
return result;
}
Result:
Result of add: 15
Process returned 0 (0x0) execution time : 0.059 s
Press any key to continue.
Inside main() part of our program we can have a variable (container) that will receive what is returned when we call function addNumbers().
Then, that result (container that hold value) will be used in future operations, multiple times even, if we need that:
#include <iostream>
#include <cstdlib>
using namespace std;
int addNumbers(int x, int y);
int main() {
int container = addNumbers(5, 10);
cout << "Result of add: " << container << endl;
return 0;
}
int addNumbers(int x, int y) {
int result = x + y;
return result;
}
Result:
Result of add: 15
Process returned 0 (0x0) execution time : 0.053 s
Press any key to continue.
Sure, we can have function full detailed above main() section, and combination of direct call and indirect call (using a variable - container) will work too.
Run this code:
#include <iostream>
#include <cstdlib>
using namespace std;
int addNumbers(int x, int y) {
int result = x + y;
return result;
}
int main() {
int container = addNumbers(10, 90);
cout << "Result for 10 and 90: " << container << endl;
cout << "Result for 5 and 15: " << addNumbers(5, 15) << endl;
return 0;
}
Result:
Result for 10 and 90: 100
Result for 5 and 15: 20
Process returned 0 (0x0) execution time : 0.072 s
Press any key to continue.
No comments:
Post a Comment