section .data
msg_write db "Write ", 0
msg_one db "one", 0
msg_two db "two", 0
msg_three db "three", 0
msg_weekend db "It's the weekend", 0
msg_weekday db "It's a weekday", 0
msg_before_noon db "It's before noon", 0
msg_after_noon db "It's after noon", 0
msg_bool db "I'm a bool", 0
msg_int db "I'm an int", 0
msg_unknown db "Don't know type %T", 0
format db "%s", 0
section .bss
res resb 10
section .text
global _start
_start:
; Here’s a basic switch.
mov eax, 2
mov ebx, msg_write
call print_string
call print_num
mov ebx, format
call print_string
cmp eax, 1
je case_one
cmp eax, 2
je case_two
cmp eax, 3
je case_three
jmp end_switch
case_one:
mov ebx, msg_one
call print_string
jmp end_switch
case_two:
mov ebx, msg_two
call print_string
jmp end_switch
case_three:
mov ebx, msg_three
call print_string
jmp end_switch
end_switch:
; Using commas to separate multiple expressions in the same case statement
; Optional default case as well.
; Rotate day_flag register to simulate weekdays and weekends
; (we pretend it's a simple hardware timer feature)
; 0 = Monday, 6 = Sunday
mov cl, 5 ; Simulate Friday
cmp cl, 5
je case_weekend
cmp cl, 6
je case_weekend
mov ebx, msg_weekday
call print_string
jmp end_time_check
case_weekend:
mov ebx, msg_weekend
call print_string
end_time_check:
; Switch without an expression for if/else logic
; Non-constant case expressions.
mov ecx, 14 ; Simulate hour of the day (14:00)
cmp ecx, 12
jl case_before_noon
mov ebx, msg_after_noon
call print_string
jmp end_time_of_day
case_before_noon:
mov ebx, msg_before_noon
call print_string
end_time_of_day:
; Type switch to discover type of an interface value.
; This is exemplary as Assembly doesn't directly support types
; but we'll simulate type checking concept.
mov eax, 1 ; Simulate an integer type
cmp eax, 1
je case_int
cmp eax, 0
je case_bool
mov ebx, msg_unknown
call print_string ; Print "Don't know type %T\n"
case_bool:
mov ebx, msg_bool
call print_string
case_int:
mov ebx, msg_int
call print_string
; Exit program
mov eax, 60 ; syscall: exit
xor edi, edi ; exit code 0
syscall
print_num:
; Print number in eax (as ASCII string)
add eax, '0'
mov [res], al
mov rsi, res
call print_string
ret
print_string:
; syscall: write(int fd, const void *buf, size_t count)
mov eax, 1
mov edi, 1
syscall
ret