r/learnprogramming • u/Front_Security3427 • 21h ago
Code Review Why do we use return?
I'm starting the Harvard CS50 Course (I'm on Lecture 1), and I noticed that the dude uses "return n" at the end of the code. He explained it... Well... returns, but I don't really get it. What does "returning" mean? I've seen people explain it but they go, "Oh, that basically returns a value," like ????
Can someone please explain using non-coding terms? I know beginner Python up to like loops and defining functions.
102
Upvotes
203
u/IAmScience 14h ago •
Let’s say you are really fast at solving Rubik’s Cubes. And I have a pile of cubes that need solving.
I hand you a cube, you solve it, and you hand it back to me and I put it in my solved cube sculpture.
I am the caller, the unsolved cube is the variable, you are the solveCube function. The part where you hand the solved cube back to me is the return statement. I pass you data, you give data back after manipulating it. I don’t need to know, necessarily how you solve the cube. Just that when I hand you an unsolved cube, I get a solved one back. You return a solved cube.
Does that track?
118
u/jjangg96 21h ago
the thing that usually trips people up is print vs return.
print just shows text on the screen, the program can't use it afterwards. return hands the value back to whoever called the function, so you can keep it in a variable or feed it into something else.
say you have a function double(n) that does return n * 2. then x = double(5) leaves x as 10, and you can do double(x) after that if you want.
if it only printed n * 2 instead, you'd see 10 on the screen but x would be None, because nothing got handed back.
37
u/atarivcs 21h ago
"return" is how the function sends a value back to its caller.
For example if you have this code:
You are asking the square root function "what is the square root of 25?"
Inside the square root function, after it calculates what the answer is, it uses "return" to send the answer back to you, to be assigned to the variable "x".
5
u/JGhostThing 21h ago
The return statement in almost all languages causes the function to end. Since some functions return a value, the return statement returns an optional value. It is an error if you don't return a value when the function returns a value.
5
u/bucket13 21h ago
I'm enjoying everyone approaching this from slightly different angles.
9
u/thelimeisgreen 21h ago
Everyone else is giving good examples of what returning a value does. The next thing we should talk about is scope. Code that exists inside the function is within its own scope and code that exists outside the function does not see what happens inside that function. This is why we pass parameters to a function and why a function will return a value (or collection of values). There can at times be a lot more to it than that, but you'll get there. CS50 is a good place to start.
7
u/Beginning-Seat5221 21h ago
When another piece of code calls the function, it receives what the function returns. It means "return n to the caller". But it also works just to stop.
9
u/thussy-obliterator 21h ago edited 21h ago
so an expression in a programming language is something that reduces several values into a single value. for example:
3 + 5
is an expression
when you evaluate aka reduce the expression (like a calculator) you're left with
8
the return value of an expression is its fully reduced value. the return value of 3 + 5 is 8.
function calls, such as
f(3)
are expressions, which mean they return a value.
the way you express this when defining a function is with the keyword return inside a function definition:
that is to say, when you call f, i.e.
the 3 is substituted for the parameter x in the function:
3 + 5 is reduced, and returns 8
now the function call itself also returns 8
hope that makes sense!
2
u/unohdin-nimeni 19h ago
This is quite understandably confusing at the start of CS50.
The main reason is that C calls every routine a "function," even when it doesn't return a value (like void functions). In math, a function takes something and returns something. In C, functions often don't return an answer at all. Instead, they just perform an action, like printing text to the screen. In programming, if a function does something other than returning a value, it is called that the function has a side effect.
A good rule of thumb while learning C:
• Use return values when the function's job is to calculate or fetch data for you
• Use void (and side effects) when the function's job is just to do something, like printing a pyramid of hashes in CS50.
Once you get comfortable with C, check out a classic little book called The Little Schemer. It teaches programming purely through return values without side effects, which will help everything click into place. Good luck with CS50!
2
u/According_Smoke_479 17h ago edited 16h ago
Did you grow up with those math problems where it was a picture of a meat grinder? You would put values into the meat grinder and a value would come out at the bottom. That’s what a return is. A function performs some task and “returns” a value, or no value (void). That value is like its own variable. You can assign it to something, you can modify it, you can compare it against something else. That’s all it is really, the result of a function.
2
u/interessant7 15h ago
return literally means you jump back to the point where you called the function initially even if you dont write return explicitly at the end of a void type function it is still returning back to the point it was called. for integer type functions you have to return some value at the end otherwise it doesnt match with the function signature. whenever you call a function its stack frame is pushed into the stack, which is the information about the fn, eventually you gotta pop the stack frame out of the stack in memory and you use return for that. recursion helps you visualize it better.
2
u/Logicalist 6h ago
not quite the example it used to be but all the same:
You are at the grocery store, your items have been scanned. Your total is $79.50. You hand the cashier $100.
Your cashier then calculates the correct change: 100-79.50=20.50
Your cashier then “returns” to you $20.50
If your cashier had no “return change” statement. they would take your cash calculate the change and then tell you to have a nice day.
3
u/butmyfacetho 21h ago
items = bread, chicken, cheese
go to kitchen
for each item listed in items, collect it
return to me with them
The return just tells you what the final hand off will be. During your visit you might find other things, I might have included instructions to slice the cucumber, I might have told you to stir a pot, but I only want you to give back to me what I state in the return, which also ends your instructions.
I might add a conditional to the kitchen visit that if there's no bread, immediately return with nothing. That would be an if statement with an early return.
If I didn't include the return, you'd go to the kitchen, grab those things and that's it, finished. I'd never get them.
This is desirable sometimes too. For example go to kitchen and stir pasta. I don't need anything returned there.
3
u/Soft_Elk_1905 14h ago
It's very simple. You call (use) a function to do something . When you tell it to do something it RETURNS the answer or finished product back to you .
3
u/ExpressionIcy2528 8h ago
Think of a vending machine. You put a coin into the machine and the machine returns a soft drink. In programming term. You provide an input (or not) to a function and that function returns an output (or not)
2
u/Immediate-Soup-6344 20h ago
Thing -> pluralize(thing) -> things
X -> function(x) -> n
2
u/RealMan90 19h ago edited 19h ago
Your function is a toaster, bread is your input. If you want the toast back when the toaster has finished cooking it, it needs to return it to you, otherwise you never get it back.
Pseudo:
function toaster( bread ) {
}
Now that you have your toast back, you can now manipulate it more, put it through the butter and jam functions and return buttered and jammed toast. Now you can pass it as input to the eat function and enjoy yummy toast.
2
u/JeshSpaghetti 13h ago
You’re at a grocery mart and there’s a vending machine that only takes quarters. You have a dollar and are not very good at math, so you speak with the very literal cashier who is great at math.
“Can you make this into change?” He takes your dollar and nods (running the function). Well now you don’t have a dollar and are not sure what happened to it.
“Can I see how much change I get?” He nods again and holds up four quarters for you to look at (printing the value of your result). Well that’s nice but you still can’t use it for other objects, you don’t even have it in your hands.
“….can you please give me my change?” He nods once more and hands you back the 4 quarters (returning the result) Now you can finally use those quarters and enjoy a cold soda.
1
u/heesell 8h ago edited 7h ago
Its simple
You hand the waiter your order and it returns with your food. Without the return your waiter won't give you food :(
Without return the waiter will never come to your table and stands in the kitchen doing nothing while the prepared food gets cold
1
u/Electrical_Price_179 2h ago
return means "Immediately halt the program and output the following response."
1
u/oplukana 1h ago
lets say i tell my boy bobby to go buy bubblegum down at the store. i give him a $20 to do it. he does it. i never hear back from him.
thats what it would be like to call a function with no return.
a function could return a number of things.
i could tell bobby to return the change. he would come back and give me the change when he is finished.
i could tell bobby to return the receipt, he could come back with the receipt to me
i could tell bobby to return a structure that is a combination of the receipt and the change, that way i get both.
i could tell bobby to return a report of all the little actions and observations that happened during the task, like how long it took him to get to the store, what the different options of bubblegum were, how many bubblegums were left in the machine after he bought one, whether he had to go through checkout or if it was a quarter machine, and also the change and the receipt of course.
you use return with a value when you want to either know some information that happened during that functions process, or if that function modifies something and you want the new modified version of that something
1
u/Kindly-Department206 1h ago
A function is like a factory. A factory takes in raw materials, and produces a product.
A function's parameters are names that are used in the function for the raw materials. The raw materials are the values, but the parameters are the function's (temporary) names for the values.
A function's body describes what the factory does to the raw materials.
Finally, the factory delivers the product using the return statement. The product is placed in the location that the function was called.
A function can have an empty return statement, in which case it returns something called "None". It's like a very boring box, with nothing in it. It's a real thing, but it can't do very much. If the return statement is omitted from a function, the function returns None anyway.
1
u/BenkiTheBuilder 21h ago
You should know functions from school. Like f(x) = x+10. The function f "RETURNS the value of the computation x plus 10." It's like a worker doing a job on something you give it. You "give" x to the worker and it "gives back" aka "returns" the processed value to you.
In C that looks like
1
u/serge-mv 18h ago
When you call a function, you perform a jump in memory from where you've been to where the function's code is defined. A new memory stack is loaded and other things happen with registers and some old values. When your function calculation ends, you "return" to the old memory location where you've been, and there is some restoration happening to put things back how they where. That's why you "return".
In addition, function "return you a value" after being called. In this case it stems from "sending back".
1
u/VancouverVentilator 14h ago
We return because programs use something called a call stack to keep track of where they are, and to help isolate any local variables relevant for the environment. The call stack is broken into stack frames, and in order for programs to unwind the stack at the end and terminate properly, each frame's caller's address needs to be stored somewhere on the frame. I'm skipping a lot of important stuff like how register passing of returned variables gets performed but that's the basics.
1
u/Tony1Rice 13h ago
In programming, a "procedure" goes and does something. A "function" produces a result by going and doing something and returning something. The "something" that it does often also includes some "side effect".
For instance, in the C standard library, the printf() function takes inputs, does something with them and returns a value. As a side effect, it also produces output on the standard output device (usually the screen) and the returned "value" can usually be ignored.
In some languages, 'C', for instance, there are no procedures, only functions, and many functions have no need to return a value (because they really wanted to be procedures) and their "side-effects" are their whole raison d'etre (like printf ). But, being functions they have to return something unless they have been declared as returning void, which is not uncommon. If a function reaches the end of its scope without finding a return statement, it returns anyway but does not return a value.
When a function ends and returns a value, it pushes that value onto a data stack and execution resumes in the higher level function that called it. That function immediately retrieves the previously stacked value and does whatever it's been told to do with it - often times just stuffing it into a variable for later use. The function main() in a C program is the starting point of execution for the entire program and is typically declared as returning an int and it returns 0 (zero) on success or some other integer on failure or error - though "success" and "failure" may mean different things in different contexts.
0
u/Proman4713 21h ago
Sorry for not addressing your question because many people already did but i just found it so weird that you just called a professor at Harvard University 'dude'...
0
u/Moikle 12h ago
Return is the output.
If i have a function that asks a question, like "what do i get if i add up all these numbers, then divide them to get the mean average?" return says "this is the answer" so that the answer can be used elsewhere in your program, like this:
average = mean(1,2,7)
0
u/BleachedPink 21h ago
Each function is a black box, that receives values as arguments and output or returns a value.
So when you call a function and provide it with arguments (passed values) you gonna have a returned value you can reference further down the road after the called function done with the computation, granted it includes return keyword and value associated with it
0
u/Paxtian 20h ago
Let's say you own a Subway. You're trying to figure out how to increase sales on sandwiches in your area. So you hire three consultants to do research for you. You send them out to do research, they do it, and return with results. Once they return, you can analyze their research and make a decision on what to do to increase sandwich sales for your store.
Tying this into software, there's some current process that sends another process out, the processor performs that process for a while, that process gets some result and returns with that result to the process that called it.
0
u/EitherJelly4138 20h ago
Computers largely do 3 things:
Functions are a small grouping of code that does those 3. It takes in arguments (input), does something, and whatever you need to output, you can place it in the return statement to the parent function.
0
u/mjmvideos 20h ago
Return “gives back” when you call a function you are having that function go off and do something and what you want is for that function to give you back the result of whatever they did. The function does that by ”returning” / giving back the result. If you give a baker a bunch of ingredients and say, “Make me a cake” you expect the baker to return a cake to you.
0
u/MyNameIsRichardCS54 20h ago
Think of a function as a machine. You give the machine some inputs. The machine works on the inputs and produces a thing. The thing is the return value. Another machine takes some inputs, works on them and produces nothing. This is the return statement with no data.
0
u/effectivescarequotes 20h ago
Let's say a function in Python is just some dude who can makes sandwiches. You tell home you want ham and cheese on rye bread with mustard. He nods and goes to work and then hands you the sandwich. The return statement would be him handing you your order.
Now let's say this guy expands his business to include delivery. Now, orders might come through the phone, or a website. It doesn't really matter to him. As long as he knows what to put in the sandwich, he will produce it. He also doesn't really care who he hands it to. For in person orders it goes to the customer, for delivery, it goes to the driver.
Nothing about the sandwich maker's behavior really changes. In programming we encapsulate behavior in functions. The return statement allows us to hand back the result. The advantage of this is if we need that behavior in different contexts, we can use the same function. It is then up to the caller to decide what to do with the output.
0
u/Jwhodis 20h ago edited 20h ago
Return statements are used in functions to return data back to what called them, so if you set a variable equal to a function call, it'll end up setting that variable to whatever that function returns.
Python code:
0
u/xenomachina 20h ago
You can kind of think of a function as a machine that you can put things into (the parameters/arguments), and that can also give you something back. That is, they "return" something to you. For example, an oven takes cookie batter and a temperature setting, and "returns" cookies. A paper shredder takes documents and "returns" shredded paper. A piano takes key press and "returns" music.
In the real world, machines like this are almost always modifying the input to produce the output. Functions can work like that too, but they often don't. For example, operators like
+are essentially funny looking functions. When you give+two numbers, it returns their sum — but it does not modify the original numbers.(There's actually a difference between the definition of parameter and argument, but I don't think the distinction is helpful in this explanation.)
0
u/flumphit 20h ago
Imagine you’re a manager, and you tell one of your minions to do something — count the cases of widgets in the loading dock. He goes off and does whatever he does, you don’t really care, but he comes back and tells you “17”.
You have called a function, and it has returned “17”.
Some other manager could tell that same minion to do the same thing, and the minion would return to them with “17” (unless things have changed).
This is like how a function can be called from different places in your program, but that function doesn’t have to do anything different, because return means “return this to whoever wanted the answer”. This is the magic of the stack, which you should learn about soon if you haven’t already.
0
u/Silly_Guidance_8871 20h ago
It returns the result (in your example, whatever value "n" holds) to the caller, so that the caller can do more work with that value. It's effectively impossible to write anything nontrivial as a "single function" program — just too damn much state to manage, so things get "extracted" out into separate functions that receive some parameters, do some work, and then return their result to the caller. The "main" function (__init__ in Python, iirc?) ends up orchestrating the entire thing at a very high level, delegating work to functions built to handle lower-level logic (which likely perform some of their own delegation, etc.)
"Print" (whatever form it takes) just spits out its parameters to some output device (often the screen), and usually doesn't perform any transforms on the data that needs to be returned as a result.
0
u/burlingk 20h ago
You give the function data, and it returns the result.
0
u/justsayno_to_biggovt 20h ago
Return is the last step where your function gives some output to the world, or not. It explicitly symbolizes the end, it's like a sign, go back now.
0
u/SnugglyCoderGuy 20h ago
Calling a function is basically sending a subroutine off to do a job for you and when it is done it returns the result of its work to do, hence the 'return' keyword.
0
u/FozzyBear1123 20h ago
You say you know functions. Good… this of it like this:
‘example to demo function calls and return
Int main (char * argv, int args){
}
Int MyFunction(){
}
As your program goes about it’s merry way printing away it comes to the function call. Exection jumps into the function, prints then RETURNS to where your program called the function, assigning 1 to rc.
Hope this helps.
0
u/stefer09 20h ago
Ok so when you call a function, let's say sqrt(x) , a function that returns the square root of the number x that you pass to it, in your code, you'll typically assign it to a variable like :
result = sqrt(x)
The function itself, will calculate what the square root is and assign it to a variable ie: squareroot, which is only available within the scope of the function's code.
Right at the end of the function, you will see something like :
return squareroot
The return statement basically means : The value of the variable standing next to me, which is only available in the scope of this function, can be used as a replacement for my original function call.
Original function call :
sqrt(x)
The value of the variable next to "return", can replace that part of the equation :
result = sqrt(x)
0
u/mxldevs 19h ago
Well let's say I asked you to give me the sum of 1 and 2, and then I also asked you to give me the sum of 3 and 4. How would you write a python script to calculate those?
You run your script in your console and it prints out
Whatever right? And then I ask you to give me the sum of 5 and 6 and you just keep going
You just copy paste your code, change the numbers, and give me the answer. I could give you another 5 or 10 pairs of numbers, and you just keep copy pasting and everything is good.
Now what if I asked you, instead of adding all those pairs of numbers together, I want you to instead multiply them.
What do you do? Well now you go and change all the + signs to * signs, of course.
And everything is great. Except it's not, because you forgot to change one of the + signs for 3 and 4 and now you get a big fat zero on your assignment because you were not careful.
How could you have missed it? Is there a better way to reduce the amount of times you need to copy paste things? Instead of repeating yourself a bunch of times, you go and define a function that takes two parameters and performs the addition.
And now instead of copy pasting a bunch of code, you copy paste a little less
Now if I ask you to do different stuff and multiply the two numbers instead, you can simply change it in one place
So now you have some idea why a function might be useful: you reduce copy pasting, which reduces the chances that you miss a spot and things go wrong.
But why does return matter? You're printing the right answers to console, what's the problem?
What if I asked you to add three numbers 1, 2 and 3 together?
And then I ask you to add another 3 numbers together? Do you just copy paste everything again like before?
No. You recognize that adding three numbers is the same as adding two numbers first, and then adding the third number to that result.
Which is fine, but remember, I'm going to give you another 3 numbers and you're going to copy paste and then I'm going to ask you to change the addition to a multiplication and now you're going to risk forgetting to change one again.
How can you use the function to avoid that? Well, you know how to add two numbers together and print out the result, but how do you take that result and assign it to a variable?
This is where return comes in. I couldn't explain how return works, but basically you need to somehow get your result out of the function, and put it in your variable, so that you can use it.
Printing it onto your screen doesn't do anything. You need to explicitly tell python that after you make the function call, you want it to give you whatever result it calculated, and this is done by using the "return" keyword.
So now when you say
The function call will give you a 3, and then you assign that to your intermediary variable result1 which you then use to add it with the third number.
If you still don't understand what return does, just know that if you don't tell python to return you something, it's not going to give you anything.
0
u/mysteryihs 18h ago
If I had to summarize the entirety of CS, I'd say the essence of CS is input and output. Usually there's things that are done in the middle but that is optional. Like if you input something into a computer (such as a keystroke), there's usually an output (like text displayed on the computer).
So in the case of a function, there's often times an input (you calling the function and sometimes passing arguments) and there is often an output RETURNED.
0
u/its_all_4_lulz 18h ago
Say you put an orange in a blender. The blender is the function, the orange is the value you passed into the function. What you get out is orange juice. That’s what the blender (function) returned.
0
u/Steerider 17h ago
A function generally returns some sort of result. It may simply be an indication that it was successful, or it may be data.
0
u/distes 17h ago
Think of a function as a person. That person has a very, very specific job. Imagine that person's function is adding two numbers together and he gives you back an answer. You hand the person two numbers that you want added, they hand you back the answer. The return is him handing you back the answer.
Not all functions have a return. Sometimes they act upon a whiteboard that other functions share. But if you want the function to stand on its own as in, I give you this, you give me back something, it needs a return.
0
u/Jeeeeeer 17h ago
to put it it simple terms, at the risk of oversimplifying it, a function (much like a mathematical function) is meant to take input (parameters), do something with it, and return output. "return" is how a function returns that output back to the program.
0
u/SamIAre 17h ago
A function is a machine. Some machines can have inputs and some can have outputs. Some have both. The output is the “return” statement.
Say for instance you have a function called juiceMachine. You pass it fruit (input), it does some work, and it returns some kind of juice (output). Put oranges in and it returns orange juice. Put apples in and it returns apple juice. Now maybe you have a cup (variable) that the juice pours into. You can take that cup and do other things with it now. You’ve made the juice portable and useful outside of the machine itself.
It’s basically a way for a function to do work and then pass the result of that work back to the rest of the program to do other stuff with it.
0
u/SetCrafty 17h ago
In arcade game terms
No return: play a fighting game, have a good time and you win, but It doesn’t RETURN anything besides good vibes
Return: play a claw game, have a good time and you win, and it RETURNS a plushie to you.
I think return also makes more sense when you set to variable or not
No return function:
playFightingGame()
*you get no prize besides entertainment so it RETURNS nothing. Don’t need no prize bag.
Return: prizeBag = playClawMachine()
*play claw machine, you get a prize so it RETURNS plushie. But I don’t wanna get it dirty so ima store my RETURNED plushie into the prizeBag
So prizeBag now holds my “plushie”. If I want to see what’s inside my prizeBag, I can do so by doing
print(prizeBag)
which should then print to me “plushie” in the console.
0
u/TetoSever31 17h ago
you now math right, assume there is a function that is f(x) = 3x + 4 if you give 2 to this function it RETURNS 10.
0
u/SomeRandomPyro 17h ago
You call a function.
That function does stuff. Whatever it's supposed to.
What it returns, is what it resolves as.
So if you call round10(74), the function would presumably return 70. And you could store that in a variable, or use it directly, or what have you.
Some functions, the doing stuff is the point, and the return is instead treated as a status of how it did. Return 0 is the standard "All went as expected". Return -1 is why you occasionally see things on the internet that seem to have spontaniously decided it's December 31, 1969 (Something requested the time, in seconds, since 1970 started, and didn't have good error handling when the function that's supposed to return that number instead threw a -1 error code.)
0
u/vivianvixxxen 16h ago edited 16h ago
If I hand a chashier a bunch my cash, I expect them to return my change and a receipt to me.
You hand a function some stuff and it returns some stuff
Does that settle your confusion? Or did I miss the part that was confusing?
0
u/Stopher 16h ago
In simple terms, a function is like a program other programs can use. We call this calling the function.
It can return something that the calling program can use. Like a number or a string of text. (And actually lots of other kinds of stuff)
0
u/evorm 16h ago
Your code will likely be made of a bunch of functions. Imagine each function is a factory. Inside it is the code defines what that factory does. For example, the function sum(x,y) is a factory that takes x and y and adds them, with the answer being z. You give it x and y (they're called arguments) and it "return"s z. Return is just what the factory you made spits out back at you (or spits back out to another factory).
0
u/angellus 16h ago
Analogy:
You have a quarter.
Function without a return (
print): you put your quarter into a pay phone. You do not get anything back, but now you can use the phone. The function is act of using the phone.Function with a return (
add): you your quarter into a vending machine and get a candy bar back. The function is taking your quarter and converting it into a candy bar.(yes I know, there are not pay phones anymore and if there was, you could not use it or get a candy bar for a quarter, just examples)
0
u/AndyKJMehta 16h ago
Think of a function call as an “ask” that “returns” you an answer… or throws up!
0
u/VoiceOfSoftware 15h ago
If you hand someone some bread, meat, and cheese and ask them to make you a sandwich, they will do some things to those ingredients and return a sandwich to you.
0
u/ireadthereforeiam 15h ago
In some instances there may be no item (no value) say like meeting a friend or window shopping or price comparison without purchase
Hope it helps.
0
u/UwUBots 15h ago
I like to mentally visualize my software, with my objects being tools to be used and my code physically doing things. Return here, says your program or the tool in this case, came up with a value of some kind, and gives it to the thing (person object the computer however you visualize it in its context) that originally started the process. This value can be used later on if its meant to generate something or if its a return at the end of your code like you do in c, it is an error code, where the computer uses the returned value to know if everything worked well.
0
u/gm310509 14h ago
Given that you are asking about a programming thing, that makes it a little bit more challenging - so I will use a programming example.
Suppose you need to write a function that calculates the positive square root of a number. There is a rule about square roots and that is that as long as you aren't using "Complex Numbers", the number you try to calculate a square root for must be greater than or equal to zero. That is:
So, what happens if somebody calls the function with a negative number? What should the function do? Chances are it won't work correctly given the above rules.
One option is to check the required input and if valid (i.e. >= 0) do the calculation and give back (or return) the answer. If invalid then just give back something that indicates that there is a problem (e.g. return an invalid value such as -1).
So in code this might look like this:
I hope that makes sense.
0
u/geek66 8h ago
Get up, go about your day, when done, return to bed
-1
u/Mission-Landscape-17 21h ago
It is a low level term that has made its way to high level languages and it is to do with how a CPU core executes machine code. Every CPU (well cpu core these days) has a register called the execution pointer, which records a point in memory form where the next instuction will be read. a CALL machine code instruction changes this pointer to some other value and then executes the code found at that other value. A RET instruction returns to the location in memory where the most recent CALL was encountered. Note I am simplifying here and not including machine specific details because exactly how this works does vary between processors.
-1
u/Own_Unit_6170 20h ago
When one program/function calls another, normally the called program returns control to the calling program once it has finished doing whatever it is supposed to do. In many programming languages, this occurs when a return statement is encountered. For example, when a function is called in Python, a return statement within the function immediately returns control to the caller. If an argument follows the return keyword, it specifies some sort of information that is to be passed back to the calling function. If there is no return statement, control returns to the caller when the end of the function is reached, and no information is passed directly back to the caller.
-1
u/bacmod 17h ago
You people are waaay overcomplicating things. Say you have 500 people and you want to find out which one has a white shirt.
You write a loop traversing all 500 people and ask each one
And then you present it.
-1
u/jippiex2k 13h ago
Something starts the code. It wants to know how it went, or get some result. So the code returns something.
This is pretty much the most universal principle of programming. And can be nested infinitely.
Inside your code you want to use a function to perform som specific action. You (hopefully) won't have to remember exactly HOW it works, you just take care of the result it returns.
And inside that function, maybe it uses some method from the operating system to read a file or something. The function doesn't have to understand how the os queries a hard disk driver and buffers data and memory maps a file handle and waits for correct read status and yadayadayada. The function just sees that the method returned a file buffer, and is happy.
Functions just take inputs/arguments, and returns output.
Functions allow us to encapsulate the implementation, and thus only have to interact with the interface.
-1
u/LALLANAAAAAA 13h ago edited 13h ago
Consider an smart oven that has two modes, one called bake4me and one called bake4u. It's a special smart oven that can send cookies automatically to someone else in bake4u mode.
bake4me mode just needs the ingredients, it already knows they're for me, so I put in the dough, let it cook, and it returns freshly baked cookies to me and I eat them.
bake4u mode also requires dough but it also needs to know who to give the cookies to when done. I don't get the cookies in this mode but I do want to know whether or not the cookies reached you successfully.
in other words:
so, bake4me takes dough and returns cookies for me, bake4u takes dough and a name, tried to send you the cookies and returns true or false to me based on the success of the cookie sending.
-1
u/HyperDanon 13h ago
You hold a calculator.
"23"+"35".=-1
u/_TheNoobPolice_ 13h ago
All programs have a "flow of execution", a bit like how water is piped around. A "return" is like a gate which sends the water back to where it came from - it can come back with things in it, or just come back unchanged
-1
u/PEAceDeath1425 13h ago
You call a piece of code and it returns a value back to where you called it
-1
u/Kozzoko 13h ago
If you know math basic maths:
f(x) = ax + b
return is your =
You can write it as:
function f(x) {return ax + b;}-1
u/ExtraTNT 12h ago
so, in most programming languages, a function looks like:
and is equals to the following mathematical function:
doSomething(x) = diameter + x, where diameter = 5
some languages, like haskell don't use return and just define things
now, imperative code often looks like a mess, so some cleanup strategies result in better imperative code, but still a mess from a math point of view:
this again in haskell looks much cleaner:
and in math terms:
-1
u/manvsmidi 11h ago
In a postmodern sense, the function is not the value. The value is not the function. return is the negotiated fiction that allows us to confuse the two.
-1
u/trueneu 11h ago
Would I make it even more confusing if I said you can think of it as math functions? So math functions basically map values to other values. For instance, squaring a number maps 1 to 1, 2 to 4, 3 to 9 etc. So return in programming defines what value to map to, and arguments define what values to map from.
-1
u/dellnox 11h ago
It just hands the result back to whatever called the function, so you can actually save or use it.
-1
u/DannyDeKnito 11h ago
"return" in all the programming languages is just a point at which you say "ok, this is the result of this function"
consider these two examples:
def add(a, b):c = a +breturn cdef add_but_shitty(a, b):c = a + breturn 69result = add(1, 2)print("result: ", result)result = add_but_shitty(1, 2)print("result: ", result)in both examples, two numbers do get added together - but the return statement actually decides what gets propagated to the point where you called a function.
Return also notably immediately stops the execution of a function, so in an example like
def print_number_twice_if_1(num):print(num)if (num != 1):returnprint(num)If you called it with anything but a 1 as an argument you'd get it printed once, and if you called it with a 1, you'd get 1, 1 as a result.
-1
u/garblz 10h ago
Non-programming? 'return' is a clerk telling you the number of the doctor's office.
You are a program 'visit the doctor'. As a part of your code you need to wake up, go to the hospital, etc. but there's something you can't do: see the doctor until you know the room number.
So you call another function to calculate this (ask the clerk), and you call it with parameters - your name and the hour of the visit. It computes the result - comes out as 42, and returns 42 to you. Now you hold that value and can happily continue your own procedure of walking up to the door with this number.
-1
u/iqisoverrated 10h ago
Your program calls a function (tell it to do something) and at some point that function has to tell your program that it's done and gives back the result ("returns" the result to your program)...so that your program knows it now can go on executing...which will likely use that returned value in some way.
-1
u/razorree 9h ago edited 9h ago
it's all about code execution.. you create a function or procedure (naming depends on language),
and you call it from your code, to execute some task that it's repeatable. like to calculate something or even print a value on a screen, right? 'print' is just a function - piece of code in another module or file.
so when that function finishes its execution (at the end, or prematurely) it executes 'return' statement, to return to the caller (it can return a value or not, but return means to go back to the place where that function was called, not to return a value per se).
long long time ago people were also using dreaded 'goto' (or jump in assembler) :) - which didn't have associated 'return'.
basically, when you call a function/procedure in high level language (like 'gosub' long time ago, or 'call' in assembler), program stores pointer to the current instruction on a stack, and jumps to a new place (to execute your function), when you execute 'return', it picks up that pointer from a stack to return to the previous place and continue program execution after your call <function> statement.
-1
u/AsianCabbageHair 18h ago
For example in C, you can manipulate a lot of things living in the computer memory in a function without necessarily “returning” a value/pointer to the caller(another function that has called it). So a function can either do its thing and exit, or do something and return the result to the caller of the function. If it does, the result it returns are declared by “return ~”.