Return Statement - Overview

Overview

In C/C++, return exp; (where exp is an expression) is a statement that tells a function to return execution of the program to the calling function, and report the value of exp. If a function has the return type void, the return statement can be used without a value, in which case the program just breaks out of the current function and returns to the calling one.

In Pascal there is no return statement. A subroutine automatically returns when execution reaches its last executable statement. Values may be returned by assigning to an identifier that has the same name as the subroutine, a function in Pascal terminology. This way the function identifier is used for recursive calls and as result holder. In some other languages a user defined result variable is used instead of the function identifier.

Certain programming languages, such as Perl and Ruby, allow the programmer to omit an explicit return statement, specifying instead that the last evaluated expression is the return value of the subroutine. In Python, the value None is returned when the return statement is omitted.

In Windows PowerShell all evaluated expressions which are not captured (e.g. assigned to a variable, cast to void or piped to $null) are returned from the subroutine as elements in an array, or as a single object in the case that only one object has not been captured.

In Perl, a return value or values of a subroutine can depend on the context in which it was called. The most fundamental distinction is a scalar context where the calling code expects one value, a list context where the calling code expects a list of values and a void context where the calling code doesn't expect any return value at all. A subroutine can check the context using the wantarray function. A special syntax of return without arguments is used to return an undefined value in scalar context and an empty list in list context. The scalar context can be further divided into Boolean, number, string, and various reference types contexts. Also, a context-sensitive object can be returned using a contextual return sequence, with lazy evaluation of scalar values.

Values returned by the program when it terminates are often captured by batch programs.

Read more about this topic:  Return Statement