Why "return" is so important and what is it's relevance ??? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 7

Why "return" is so important and what is it's relevance ???

I read it in many books but I am still confused.

12th Jan 2018, 8:06 AM
Vivek Verma
Vivek Verma - avatar
3 Answers
+ 4
Every function (method) is made to solve some particular task / problem. But what, if we need to get the result of that function? The function should send that result somewhere. And that place is where it is called. So, the function do it's job and return the result (as answer) to the place where it's called. There are mainly two type functions: void - the function doesn't return a value value type (int, string or other) - the function should return to the caller an int or string type value (depends from the type). So: 1. We call the function 2. The function do something 3. The function return value (if it's defined as value type function) or nothing (if it's void type) Example of value type: int sum(int a, int b) { return a + b; // Returns a sum to the caller } int result = sum(10, 5); // result variable gets the sum of 10 + 5 Example of void type: void printSum(int a, int b) { cout << a + b << endl; } The keyword return is used also to escape from the function if a particular condition is met. void division(int a, int b) { if (b == 0) { cout << "Division by zero is not allowed" << endl; return; } cout << "result: " << a / b << endl; }
12th Jan 2018, 9:46 AM
Boris Batinkov
Boris Batinkov - avatar
+ 20
return functions can take data, change it about, and return it. For example: int x = 9; System.out.println(x); //Prints 9 x = addTwo(x); System.out.println(x); //Prints 11 public static int addTwo(int number){ number += 2; return number; } As you can see, this program starts wirh x set at 9. Then, the function 'addTwo' runs. It takes x as a parameter, then adds two, and returns it. Since x = addTwo(x), the value returned from the function (11) is set to x. Then, the value of x is printed again, but this time it is 11. So this is just one example of how return works.
14th Jan 2018, 7:10 AM
MaddyChan
MaddyChan - avatar
+ 4
thanks to everyone 😊😊😊😊
14th Jan 2018, 7:21 AM
Vivek Verma
Vivek Verma - avatar