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 return control from the current method to the caller, and also pass back whatever argument is sent with it. In your example,GivePoints
is defined to return an integer, and to accept an integer as an argument. In your example, the value returned is actually the same as the argument value.A returned value is used from somewhere else in your code that calls the defined method,
GivePoints
in this example.would mean that
currentPoints
gets assigned the value of 1.What this breaks down to is that
GivePoints
is evaluated. The evaluation ofGivePoints
is based on what the method returns.GivePoints
returns the input, thus,GivePoints
will evaluate to 1 in the above example.just a guess for your original goal
so return will return the updated value of Points
if this is not your case the code should be
Return
will always exit (leave) the function, anything after return will not execute.Return example:
Return a variable example:
Return a variable example and catch the variable that got returned:
In you example, the function is returning the exact number you are sending to it. In this case, whatever value you pass as
amount
. Therefore, the return in your current code is a bit pointless.So in your example:
x will equal 1000