11.7 Returning from a Function

The body of a user-defined function can contain a return statement. This statement returns control to the rest of the Octave program. It looks like this:

return

Unlike the return statement in C, Octave’s return statement cannot be used to return a value from a function. Instead, you must assign values to the list of return variables that are part of the function statement. The return statement simply makes it easier to exit a function from a deeply nested loop or conditional statement.

Here is an example of a function that checks to see if any elements of a vector are nonzero.

function retval = any_nonzero (v)
  retval = 0;
  for i = 1:length (v)
    if (v (i) != 0)
      retval = 1;
      return;
    endif
  endfor
  printf ("no nonzero elements found\n");
endfunction

Note that this function could not have been written using the break statement to exit the loop once a nonzero value is found without adding extra logic to avoid printing the message if the vector does contain a nonzero element.

return

When Octave encounters the keyword return inside a function or script, it returns control to the caller immediately. At the top level, the return statement is ignored. A return statement is assumed at the end of every function definition.

© 1996–2020 John W. Eaton
Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies.
Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one.
Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions.
https://octave.org/doc/v5.2.0/Returning-from-a-Function.html