Stage 0132 More flexibility to the Switch statement

Follow the development of the SharpBASIC compiler and share your thoughts and ideas.
Locked
User avatar
frank
Site Admin
Posts: 42
Joined: Sun Nov 21, 2021 12:04 pm
Location: Netherlands
Contact:

Stage 0132 More flexibility to the Switch statement

Post by frank »

SharpBASIC's switch statement 'when' has been renamed to 'by' and extended with the directives 'next' and 'done'. Previously, the directive 'fall' tested the next branch and executed it if the condition was met. This behavior has changed. Now, the fall directive executes the next branch no matter what, thus skipping the condition. The new 'next' directive does what 'fall' did previously: it tests the next condition(s) and executes the block that resolves to 'true'. The new 'done' directive leaves the switch unconditionally.

The keyword 'other' to indicate the switch's default branch has been renamed to 'any'. With these changes, the by-switch statement has become concise and very flexible.

Code: Select all

' SharpBASIC 'by' switch example with fall, next and done
' -------------------------------------------------------
option strict;

incl "lib/sys.sbi";

dim n: int = 1;

main do
  by n
    is 1, 4, 5 do
      print("this is one");
      fall;         ' skip next condition and execute its block
    is 2 do
      print("this is two");
      n = 3;
      next;         ' test next conditions, execute 'any' if no match
    is 3 do
      print("this is three");
      done;         ' exit switch statement
    is 7 to 10, 12 do
      ' If this block is executed the 'any' branch can be executed with
      ' 'fall' or 'next'
      print("this is four");
      fall;
    is any do
      print("this is any");
  end
end
Last edited by frank on Fri May 23, 2025 2:45 pm, edited 1 time in total.
It's only logical.
Locked