[C++]What's the difference between these returns?
Sorry for all the questions but im the process of learning at the moment and i apologize.
Anyways.
Below are two scripts. Apparently, the first one is the correct way of coding, and the second one has a few changes in it near the end. Why does the second script not work and what's the difference?
First Script:
Code:
#include <iostream>
using namespace std;
int mult ( int x, int y );
int main()
{
int x;
int y;
cout<<"Please input two numbers to be multiplied: ";
cin>> x >> y;
cin.ignore();
cout<<"The product of your two numbers is "<< mult ( x, y ) <<"\n";
cin.get();
}
int mult ( int x, int y )
{
return x * y;
}
And here is the second one which won't work:
Code:
#include <iostream>
using namespace std;
int mult ( int x, int y );
int main()
{
int x;
int y;
cout<<"Please input two numbers to be multiplied: ";
cin>> x >> y;
cin.ignore();
cout<<"The product of your two numbers is "<< mult ( x, y ) <<"\n";
cin.get();
}
int mult ( int x, int y)
{
return mult ( x , y );
}
Thanks to all who answer
Re: [C++]What's the difference between these returns?
In the latter one you're doing a so-called recursive call. By saying return mult(x, y); you're saying that return whatever value the function mult returns with parameters (x,y), so mult will call mult again, which will call mult again, and so on... never getting to a point that a simple value is returned.
The latter is the same as
int mult(int x, int y)
{
int z = mult(x, y);
return z;
}
Re: [C++]What's the difference between these returns?
alright that makes sense. Thank you. But one more question, why do we even need that last part if we just put in "cin.get();"? shouldn't it return it if we put that in?
Re: [C++]What's the difference between these returns?
I don't understand your question. What do you mean with "last part" and "it"?
Re: [C++]What's the difference between these returns?
I'm not sure if I understood the question, But you need the cin.get(); because when you run the code(Not in debug mode) when it will finish it will exit and you wont be able to see the result, By adding cin.get(); you're making your code wait for some input and by that allowing you to see the last line the program wrote in the console.
Re: [C++]What's the difference between these returns?
Quote:
Originally Posted by
Noob4Ever
I'm not sure if I understood the question, But you need the cin.get(); because when you run the code(Not in debug mode) when it will finish it will exit and you wont be able to see the result, By adding cin.get(); you're making your code wait for some input and by that allowing you to see the last line the program wrote in the console.
Yes. The console will not close that way unless you press a key.