It's hard for me to grasp what exactly a return statement is doing. For instance, in this method...
public int GivePoints(int amount)
{
Points -= amount;
return amount;
}
Even if I place any random integer after return, the GivePoints method still does the exact same thing. So what is it that the return statement is doing?
Return will exit the function when calling it. Whatever is below the return statement will thus not be executed.
Basically, return
indicates that whatever operation the function was supposed to preform has been preformed, and passes the result of this operation back (if applicable) to the caller.
Return
will always exit (leave) the function, anything after return will not execute.
Return example:
public int GivePoints(int amount)
{
Points -= amount;
return; //this means exit the function now.
}
Return a variable example:
public int GivePoints(int amount)
{
Points -= amount;
return amount; //this means exit the function and take along 'amount'
}
Return a variable example and catch the variable that got returned:
public int GivePoints(int amount)
{
Points -= amount;
return amount; //this means exit the function and take along 'amount'
}
int IamCatchingWhateverGotReturned = GivePoints(1000); //catch the returned variable (in our case amount)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With