I don't understand this 'return' stuff. where exactly does it return to?. For instance, if I type 'return 0' or 'return 1' or 'return sum', what is the difference?. Where does 0,1,sum return to (or what does it return?) and what is the reason for the return? | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
+ 1

I don't understand this 'return' stuff. where exactly does it return to?. For instance, if I type 'return 0' or 'return 1' or 'return sum', what is the difference?. Where does 0,1,sum return to (or what does it return?) and what is the reason for the return?

17th Nov 2016, 4:02 AM
Cody Arthur
Cody Arthur - avatar
4 ответов
+ 1
in main, return 0 signals the end of the program. If you call a function that has a return type of int, and have sum also declared as an int and you return it, the value is returned to the function that called it. Most of the time you would use something like this int main() { int ReturnedInput = UserInput(); } int UserInput () { int Input; cin >> Input; return Input; } in the above example, when you return the users input, it will get stored into the ReturnedInput variable in main.
17th Nov 2016, 5:11 AM
scott johnson
scott johnson - avatar
+ 1
//for eg SomeFunction(int x) { int res = x*2; return res; } in this case the input value of x will be doubled however if you change "return res" to "return 1" then the output will always be 1 regardless the value on input
17th Nov 2016, 9:36 AM
Ziyaan Hassan
Ziyaan Hassan - avatar
+ 1
So from the explanations, I understand that the 'return' statement contains the value of a function and is necessary in case that function is called in another function. But in the case of 'int main', return 0 simply suggests that the code has run successfully. Am I right?
17th Nov 2016, 7:23 PM
Cody Arthur
Cody Arthur - avatar
+ 1
yes, return 0 indicates the program executed and ran without errors. After a little research, the 0 returned by main is passed back to the operating system and indicates the program ran successfully. return values can also be used to indicate a specific type of error when you do exceptions or other error handling techniques. -1 is a value you will see a lot in common C++ functions that the language provides to indicate an error.
17th Nov 2016, 7:27 PM
scott johnson
scott johnson - avatar