✅ Newbie question - what exactly does return do?
If I have this piece of code... what exactly happens when the return statement is reached? I understand it exits the current function, but then what is the state of the programme?
6 Replies
In this case, it just exits the method (or function, same thing) and returns back to the place you called the method at.
Thinker
REPL Result: Success
Console Output
Compile: 599.862ms | Execution: 75.520ms | React with ❌ to remove this embed.
Here you can see how, once the
return;
is reached, execution goes back to where the method was called.
However return
also has a second (arguably more important) usage: in your case the method NameInputExists()
returns void
- which essentially means that the method only does things like writing to the console or similar - but if you were to change that to int
for example, now the method would have a return value.
Take this method for example
This is a method called Add
which has a couple of properties: it takes two parameters - a
and b
, both of which are integers -, it returns int
which means that it should "give back" an integer to the caller, and the value it returns is the result of a + b
.
So you might use this method like this:
I hope that somewhat made sensegreat. Many thanks!!
$close
Use the /close command to mark a forum thread as answered