0
C++ Not really a question, just some examples of calling an ext function multiple times (tips welcome!)
I'm almost finished the C++ course but found it moves fairly quickly thru functions/classes without enough practical examples to really reinforce how using them can simplify the code in int main (especially as I near the finish and find the last two queue challenges a little difficult, I've completed all the other lessons and now trying to review everything). So I'm creating my own practices to help me learn and thought others might find it useful or have some good tips to offer. Im still not sure about using the "return" in functions and how to benefit from that. https://code.sololearn.com/cncnI0D1xwEw/?ref=app
4 Answers
+ 1
return lets us assign the result of the function to another variable.
#include <iostream>
using namespace std;
int sum(int x, int y){
int total = x+y;
return total;
}
int main() {
int x, y;
x = 11;
y = 23;
int z = sum(x, y);
cout << z << endl;
}
you would get garbage value and a warning if you don't have a return statement for functions specifying one.
int sum(int x, int y){
int total = x+y;
cout<<total<<endl;
}
+ 1
Bob_Li
Thanks Bob, makes sense. So that can further be used for somethng like this (yes, it's kinda non-sensical but works...)
#include <iostream>
using namespace std;
int sum(int x, int y){
int total = x+y;
return total;
}
int sub(int x, int z){
int total = x-z;
return total;
}
int main() {
int x, y;
x = 11;
y = 23;
int z = sum(x, y);
cout << z << endl;
int a = sub(x, z);
cout << a <<endl;
}
One question: does return total (for example) only return the value to int main or is it now a global var that could be accessed by other functions?
I guess I could just test it... š
+ 1
it's local to the function. you can pass the value to main or other functions.
use pointers if you want to mutate values outside the function.
0
Here's another example calling a few different functions from int main using arrays and a "for" loop.
https://code.sololearn.com/cfd3S5cpZxtb/?ref=app