L1VM - course 02

switch

In the first part of the course you did learn how to write a simple “Hello world!” program. And what the “if” and “if+” statement can do.

But what if you have to do multiple checks if a variable has some value and do something? In this case you can use the “switch” statement:

(switch)
	(y 23_const ?)
		print_s (23_str)
		print_n
		(break)
	(y 42_const ?)
		print_s (42_str)
		print_n
		(break)
(switchend)

The “?” stands for branch if equal. So if “y” is of value “23_const” the string “23_str” is printed. Note: the “(break)” statement does not “break” the “switch” statement. It Is just like an “endif”. So if the first switch statement is true then it continues with the “(y 42_const ?)” comparison. And there is no “default” statement like in C or C++ for example!

Here is a full example:

// switch.l1com
// Brackets - Hello world! switch
//
#include <intr.l1h>
(main func)
	(set int64 1 zero 0)
	(set int64 1 x 23)
	(set int64 1 y 42)
	(set string s 23_str "y = 23")
	(set string s 42_str "y = 42")
	(set const-int64 1 23_const 23)
	(set const-int64 1 42_const 42)
	(set string s hello_str "Hello world!")
	(set int64 1 a 0)
	// print string
	print_s (hello_str)
	print_n
	((x y *) a =)
	print_i (a)
	print_n
	(switch)
		(y 23_const ?)
			print_s (23_str)
			print_n
			(break)
		(y 42_const ?)
			print_s (42_str)
			print_n
			(break)
	(switchend)
	exit (zero)
(funcend)

Here is the output:

$ l1vm prog/switch -q
Hello world!
966
y = 42

In this program “intr.l1h” includes the macros for the interrupt functions. So you can use “print_i” and “print_s” for example instead of the interrupt statement with the number codes.

3: math