What exactly does return do. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

What exactly does return do.

I usually just put return at the end of a function because I was told I have to. and because I don't know what it does I always put return 0 to stay neutral and hope I don't run into errors lol. What exactly does it do though and how do I know what I should tell it to return? in words a dumb person can understand please 🙄

31st Aug 2017, 3:31 PM
RevanChan
RevanChan - avatar
5 Answers
+ 4
Return simply returns data back to whatever called the function. In many cases, you'll send something off to a function and it'll return the result back so you can utilize it. In the case of the main loop, it's returning an exit code to the OS so it can generate errors if needed ( 0 or 1, Success/Failure). In the case of the method being void, that means it doesn't return anything, but simply performs whatever its function is.
31st Aug 2017, 3:49 PM
AgentSmith
+ 10
Why not try it out for yourself. Return statement specifies the value to be returned back to where it is called. E.g. int sum(int x, int y) { return x+y; } int main() { std::cout << sum(1, 2); return 0; }
31st Aug 2017, 3:46 PM
Hatsy Rei
Hatsy Rei - avatar
+ 9
The return statement allows a function to immediately transfer control back to the calling function (or, in the case of the main function, transfer control back to the operating system). The return statement accepts an expression, which is the value passed back to the calling function. when the function is declared as int main() then it has to return a int value so return 0 is used.
31st Aug 2017, 3:37 PM
P R
P R - avatar
+ 2
who minus 1'd me? I asked a legitimate question...
31st Aug 2017, 3:57 PM
RevanChan
RevanChan - avatar
0
actually return returns the memory taken by data type int or any other data type but when u will use void in declaring u didn't need to return any value to os
31st Aug 2017, 3:39 PM
rahul negi
rahul negi - avatar