LoginLogin

SWITCH/CASE Library

Root / Submissions / [.]

computableeCreated:
Version:Size:
Were you one of many who were upset that SmileBASIC did not come with a switch/case-like command? I have a solution! My program!

Instructions:

Switch/case statements are used in languages like C where you have one variable with many possible values, and you want to do something different for each value (e. g. If A==1, do this. If A==2, do this. If A==3, do this, etc.). Instead of writing tons of IF statements comparing your variable each time, a switch statement does the majority of the work for you! The first step is to load PRG:SWITCHFN into a program slot not in use. Then add USE [program slot SWITCHFN is in] to the top of your program. If you are testing a string, use this format: SWITCH$ String to test IF CASE$("comparison 1") THEN 'insert code here ENDIF IF CASE$("comparison 2") THEN 'insert code here ENDIF IF CASE$("comparison 3") THEN 'insert code here ENDIF 'et cetera ENDSW If you are testing an integer or decimal, use this format: SWITCH Variable to test IF CASE(comparison 1) THEN 'insert code here ENDIF IF CASE(comparison 2) THEN 'insert code here ENDIF IF CASE(comparison 3) THEN 'insert code here ENDIF 'et cetera ENDSW Example: USE 3 VAR S$="Hi!" SWITCH$ S$ IF CASE$("Hi!") THEN PRINT "Hi there!" ENDIF IF CASE$("Hello!") THEN PRINT "Hello there!" ENDIF IF CASE$("Sup?") THEN PRINT "Sup with you?" ENDIF ENDSW 'Output: Hi there!

This looks really nice! Though I'll probably just stick with my many IF's and ELSEIF's.

At first, when I looked at this library, I was like "pish that's what IF and ELSE does!". But then I started using JavaScript, and I was taught how to use SWITCH and CASE and I was like "WOW this will change everything! Anyways nice program. I like the way you did it.

I'm confused... What advantage does this have over comparison? I mean, drop the SWITCH and ENDSW statements, and replace every CASE(K) with (TEST%==K) and you get the exact same thing. Am I missing something? This does help a little bit with readability, but not by much.

The key issue with this library is it's required use of IFs, which the switch statements were intended to replace.

SWITCHes cannot be nested. You could fix this with VAR TOSWITCH$[0], in the SWITCH procedures use UNSHIFT, in the CASE functions, instead of TRIGGERED% use LEN(TOSWITCH$)>0, instead of TOSWITCH$ use TOSWITCH$[0], and in ENDSW use SHIFT.

It would be called SELECT CASE, since that's what it is in qbasic. SELECT CASE variable CASE value: do something CASE othervalue: do something else ENDSELECT

I use the ON command a lot, it works similarly and is good for my purpose.

Why was this removed? This would be very useful in my programs.