Below is a basic example of returning a value. My question; is there a way to send multiple values back. Say X = 2 and Y = 5. Could I send back both using the return. And then on the Main use X and Y where I need it. Or is it not possible or too complicated to be of practical use?
void ball();
int stone();
int main() {
ball();
int pebble = stone();
cout << endl << " " << pebble << endl;
return 0;
}
// function definitions below:
void ball() {
cout << " This is a basic return function " << endl;
}
int stone() {
int y = 5;
int x = 10; // Can we send a y value back if the function was altered?
return (x);
// Does a return, just deal with one value?
Yes a function can only "return" one value. However you can pass values into the function by reference to allow changes made to the variables in the function to be reflected in the calling function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
usingnamespace std;
void stone(int& x, int& y)
{
x = 10;
y = 2;
}
int main()
{
int x = 0;
int y = 0;
stone(x, y);
cout << x << " : " << y << endl;
}
Ashertech- I will give that a go now and see if it works.
I've also learned in programming, or concise programming, to return a sum, rather than type it out separately. These little things, help a lot in reducing the bulk.
What I am trying to-do is tie up the loose ends and understand all the possibilities with Returning. I think we have done that now.
I'm going to be surprised when I see real programs at the end of my studies, to see what the code looks like in the real world. I'm a long way off from that.
Ashertech. The compiler only reads the first Return and ignore the second. There are no errors showing. I think the Return option is a one entry one time delivery service. Does anyone else agree?
Ashertech- I will give that a go now and see if it works.
As pointed out by TheIdeasMan consecutive return statements will not work.
Execution will reach the first return statement and exit the function. The second return statement will never be reached.