RETURN Return From Function

Section: Flow Control

Usage

The return statement is used to immediately return from a function, or to return from a keyboard session. The syntax for its use is
  return

Inside a function, a return statement causes FreeMat to exit the function immediately. When a keyboard session is active, the return statement causes execution to resume where the keyboard session started.

Example

In the first example, we define a function that uses a return to exit the function if a certain test condition is satisfied.

     return_func.m
function ret = return_func(a,b)
  ret = 'a is greater';
  if (a > b)
    return;
  end
  ret = 'b is greater';
  printf('finishing up...\n');

Next we exercise the function with a few simple test cases:

--> return_func(1,3)
finishing up...
ans = 
  <string>  - size: [1 12]
 b is greater
--> return_func(5,2)
ans = 
  <string>  - size: [1 12]
 a is greater

In the second example, we take the function and rewrite it to use a keyboard statement inside the if statement.

     return_func2.m
function ret = return_func2(a,b)
  if (a > b)
     ret = 'a is greater';
     keyboard;
  else
     ret = 'b is greater';
  end
  printf('finishing up...\n');

Now, we call the function with a larger first argument, which triggers the keyboard session. After verifying a few values inside the keyboard session, we issue a return statement to resume execution.

--> return_func2(2,4)
finishing up...
ans = 
  <string>  - size: [1 12]
 b is greater
--> return_func2(5,1)
[return_func2,4]--> ret
ans = 
  <string>  - size: [1 12]
 a is greater
[return_func2,4]--> a
ans = 
  <int32>  - size: [1 1]
 5  
[return_func2,4]--> b
ans = 
  <int32>  - size: [1 1]
 1  
[return_func2,4]--> return
finishing up...
ans = 
  <string>  - size: [1 12]
 a is greater