ELI5. What does “return” do in programming? I read about it a lot and still dont understand the purpose.

354 views

ELI5. What does “return” do in programming? I read about it a lot and still dont understand the purpose.

In: 0

10 Answers

Anonymous 0 Comments

When you have a bit of code that will be run over and over again with different inputs each time, you write a function. We need a start and an end to the function. Multiple ends are ok, but we always need to make sure we end it. If we don’t don’t the function, the code will just keep going, reading whatever is next after the function, thinking it’s still in that function, and thats not ok. It could read anything, maybe even stuff you haven’t written because it’s not going through the code, but rather it goes through the memory of the computer and who knows what bits it will interpret as commands, what it will overwrite or what mischief it gets up to.

Let’s write a function called divide

Divide(a, b)

If(b==0){

Return null

}

C = a/b

Return c

This is properly written code. If I instead left out that “return null” the function would try to do a/0, which it can’t do.

Now lets write a function called multiply.

Multiply(a, b)

c = a * b

Return c

Here, if we left out return, the code would just keep running on and on through whatever memory address follow multiply. Let’s say our function divide is kept there, then instead of returning a * b, it would return a/b

You are viewing 1 out of 10 answers, click here to view all answers.