The return statement is used to terminate the execution of a function and transfer program control back to the calling function. In addition, it can specify a value to be returned by the function. A function may contain one or more return statements. The general format of the return statement is given below.
return expr ;
where expr is the expression whose value is returned by the function. The execution of the return statement causes the expression expr to be to be evaluated and its value to be returned to the point from which this function is called. The expression expr in the return statement is optional and if omitted, program control is transferred back to the calling function without returning any value. ·
As we know, a function returns a value if the return type other than void is specified in the function definition or if the return type is omitted. Such a function must return a value using the return statement(s). Note that a function can return only a single value through its name.
If a function does not return any value, the return statement may be omitted, in which case all the statements within the function body are always executed before control is transferred back to the calling program. However, we can include one or more return statements (without expr) to transfer control back to the calling function.
Function returning a value
The function given below accepts two numbers of type double and returns the larger of them which is also a value of type double.
double large(double a, double b) { double large; if (a > b) large = a; else large = b; return large; }
The function declares a local variable named 1arge, the larger of the two numbers a and b. Note that its name is the same as that of the function. The value of variable large is determined using an if-else statement and then returned using a return statement.
As a function can contain several return statements, we can simplify this function by eliminating the variable large and returning the values from both the if and else clauses as shown below.
double large(double a, double b) { if (a > b) return a; else return b; }
We can further simplify this function by using the conditional expression operator (?:)within a single return statement as shown below.
double large(double a, double b) { return a > b ? a : b; }