-
1 question anyone
Hi me again, I have a rather puzzling questonsthat none of my books help me with..
take this code: this is not my code i am working on its an examole to explain better!
Code:
#include <iostream>
using namespace std;
void IamAfunction();
int main()
{
IamAfunction();
return 0;
}
void IamAfunction()
{
// code here //
return;
}
Ok, I know you cannot return 0 to a voided function, but why does my compiler allow me to just put return with no number after it? Is it old C type synax? I am also unaware if it will have any cascading effects on the rest of my program.,,,,,
any help would be appreiciated thanks!
-
return simply implies that you wish for control to be returned to the caller of that function.
a void simply means that the caller shouldn't expect any value to come out of the function, but until that function finishes, or until a return is called, that function holds control over program flow.
You can use return; without any value because you might want to stop function execution and return control back to the main function or what not, if a certain condition was met.
Code:
void function1()
{
int a;
cin>>a;
if(a<0)
{
return;//If the person puts in a negetive value, stop the function
//and return control to the caller.
}
cout<<"Your Input was Positive!, your input was: "<<a<<endl;
}
int main()
{
function1();
return 0;
}
In this example function1 takes some input from cin, if its less than 0 *a negative number* then it stops program execution and returns control to the caller, which in this case is the main function.
The return call on main (return 0;) returns control to the operating system, with a return value of 0, (Windows doesn't use this, but linux/unix does).
But in essence just think of a call to return as a break on function execution where control is given back to whatever called the function in the first place.
EDIT: Wasn't sure if this even really answered your question, so i will add one more thing.
returns can be called at any point during a functions execution.
Code:
int add(int a, int b)
{
if((a+b)<0)
{
return 0;//We won't allow negative numbers here!
}
if((a+b)>100)
{
return 100;// Anything larger than 100 we will trunicate
}
return (a+b);
}
So as you can see return values can be put in anywhere, you can even return operations or extra function calls. Hope this helps you to understand returns a little better.