return

Summary

Exits a function and, optionally, evaluates an expression and returns the evaluated expression to the function's caller.

Syntax

return [expression];

Parameters

expression
Optional. The expression to evaluate and return. If no expression is provided, undefined will be returned.

Description

The return statement will exit the current function, and, if an expression is provided to the return statement, the expression will be evaluated (within the context of the current function) and the evaluated value is returned to the function's caller. If no expression is provided, the value undefined is returned. Execution continues immediately after where the function was originally called.

The type of the expression provided to the return statement must match the return type specified for the current function during its declaration; otherwise, a compiler error will be raised. If the return type specified for the current function is void or function, a return statement is not necessary. However, for any other return type, a return statement must be provided at least once; otherwise, the compiler will raise a compile-time error.

Statements appearing after a return statement will not be evaluated. The compiler will raise a compile-time warning for statements that appear after a return statement. Unimplemented

Differences to JavaScript

In JavaScript, the following is a problem due to Automatic Semicolon Insertion (ASI):

1
2
3
4
function add(a, b) {
    return
        a + b;
}

JavaScript will interpret the above code as:

1
2
3
4
function add(a, b) {
    return; // Exits the function and returns 'undefined'
        a + b; // Never executes since function already exited
}

However, this language bug is fixed in JS++ because JS++ does not do "Automatic Semicolon Insertion". Thus, semicolons are not inserted without the user's knowledge, and the first example will work as expected. In JS++, a statement ends when a semicolon is encountered, and the return statement in the first example, therefore, spans two lines.

Examples

Returning a Value
1
2
3
int add(int a, int b) {
    return a + b;
}
Prematurely Exiting Function
1
2
3
4
5
void foo() {
    bar();
    return; // Exit function
    baz(); // This will never run since the function has already exited
}

See Also

Share

HTML | BBCode | Direct Link