User Tools

Site Tools


return

Table of Contents

return

return - a control flow statement that returns control from a subroutine or function

syntax

return [expression]

- expression is optional and can be numeric or string

details

return can be used in a subroutine or function to return immediately to the code that follows on the subroutine or function call. In case of a function, an optional return value can be provided. A return statement in a subroutine cannot return a value.

In normal functions the function's identifier can also be assigned a return value. But an assignment statement to a function's identifier does not immediately leave the function. If a function's return value has been assigned, any return statement thereafter without an explicit return value will return the most recently assigned value.

In an anonymous function only the return statement can be used to set a return value and leave the function.

examples

In the following example a function sets a default return value followed by a conditional return statement.

' SharpBASIC function with return, programming example
' ----------------------------------------------------
incl "lib/sys.sbi";

decl func notZero(x:int):bool;

dim n:int = 1;
dim r:bool;

main do
  r = notZero(n);
  print(r);
end

func notZero(n:int):bool
do
  ' default return value
  notZero = false;
  ' conditional return
  if n <> 0 do
    return true;
  end if
end
Output:

-1


In the next example a limit is passed as parameter to a subroutine to break iteration and resume control where the subroutine was called.

' SharpBASIC subroutine with return, programming example
' ------------------------------------------------------
incl "lib/sys.sbi";

decl sub printIter(lim:uint);

dim limit:uint;

main do

  limit = 5;
  print("limit =" + cstr(limit));
  printIter(limit);

  limit = 10;
  print("limit =" + cstr(limit));
  printIter(limit);

end

sub printIter(lim:uint)
  dim i: itr;
do
  for i = 1 to 9 :++ do
    if i > limit do
      return;
    end
    print(i);
  end
end
Output: limit =5

1

2

3

4

5

limit =10

1

2

3

4

5

6

7

8

9

return.txt · Last modified: 2023/07/09 18:42 by admin