The return statement ends the current function and returns control in the point of invocation. It could also return value in that point. Here is the syntax and examples:
from function that does not return value:
from function that returns value:
The return value could be any valid expression that returns a value:
The value must be of the same (or compatible) type that the function was defined. For example, an int function can’t return a float value.
First you need to understand how the function call works. When you call a function two things happen
This is what we
call a transfer of control. When you call a function the control of the program
is transferred from the calling function to the called function.
The return statement returns the control to the previous routine. That function will continue its execution from the point where it was paused.
On the contrary, a function that calls the return statement is finished. It is not in a paused state and it cannot resume.
The function main is called when our program is started. Then it calls the routine sumDigits. At this point “main” is paused and sumDigits starts. The second function will do its calculations and reach the return sum; statement. Here it ends and the control is transferred back in main. Since sumDigits returns a value(the value of the sum variable), a value will appear in the place where the function was called.
The sum of the digits is 0+1+2…+9= 45. This value will appear in the place of invocation and the variable sum will take this value. Then we print that value and return from the main function, which ends our program.
Note that in the example above we didn’t need to use the return statement in the main function. If a function is defined as void it does not need to return a value. Such functions return control automatically when they reach the end of their body.
Still, we can use return; to end their execution from any point of their body.
Here we use the return keyword to interrupt the function printIfFound. This accomplishes two things:
If a function is defined to return a value it must use the return statement. It must also make sure that each possible outcome returns a value. This could get tricky if your routine has nested constructions and you are not careful.
If you forget the return -1; you’ve got a problem. In C many compilers will allow such “broken” code to compile, but it will not work properly. Such bugs could be hellish to find and fix. For this reason you need to plan very carefully your branches. See good practices below for guidance.
You can download and test the examples from here.
Here are the above examples, changed to follow the guidelines: