Sign in to follow this  
loachman

using return value of one function for parameter of another

Recommended Posts

Hello. How can I use the return value of one function as a parameter of another function. Like If I have a function that asks for the number of bicycles and returns that as an int. How can I use that returned int as a parameter for another function?
 int numBicycles(){
   int numBikes;
   cout << "Please enter the number of bicycles ";
   cin >> numBikes;
}

int thisWontWork(int numBikes){
    //processing code using numBikes
    //like a loop or whatnot
}


Share this post


Link to post
Share on other sites
The function that is being used as an argument must return a value for it to work. In your case, numBicycles() is defined as returning an integer, but your definition has no return statement.


int numBicycles(){
int numBikes;
cout << "Please enter the number of bicycles ";
cin >> numBikes;
return numBikes;
}



...would pass numBikes as the argument for your thisWontWork(int) function.

Share this post


Link to post
Share on other sites
Quote:
Original post by loachman
Hello. How can I use the return value of one function as a parameter of another function. Like If I have a function that asks for the number of bicycles and returns that as an int. How can I use that returned int as a parameter for another function?

*** Source Snippet Removed ***


Two ways:

1. Save the returned value of a function in a variable and pass the variable:


int ReturnSomething()
{
return 12;
}

void PassSomething(int variable)
{
cout << "You passed " << variable << "; YAY!" << endl;
}

void main()
{
int X;
X = ReturnSomething();
PassSomething(X);
}




2. Put the function where you would pass a variable to another function. When the program gets to that part, it will run the passed-in function and take whatever it returns and pass that in automatically.


int ReturnSomething()
{
return 12;
}

void PassSomething(int variable)
{
cout << "You passed " << variable << "; YAY!" << endl;
}

void main()
{
PassSomething( ReturnSomething() );
}




Keep in mind that the variable/function types need to be matching (unless you cast from one type to another but judging from your question I am guessing you have no idea about that). In case you don't know, the "void" type of a function does not return any value.

Share this post


Link to post
Share on other sites
Thanks that's almost got me there. This is for homework so I can't really post my real code.Actually my second function is returning an int too.But I get the error

function does not take 1 arguments

When I have only 1 parameter in fact.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this