if(condition){// do something}else{// do something else}
在汇编语言中,我们可以使用cmp指令进行比较,使用je和jne指令进行跳转:
其中:
je 代表 Jump if Equal
jne 代表 Jump if Not Equal
mov eax, 1 ; set eax to 1
cmp eax, 1 ; compare eax to 1
je true_label ; jump to true_label if equal
; do something if not equal
jmp end_label ; jump to end_label
true_label:
; do something if equal
end_label:
以上代码将实现一个简单的if/else语句块。
循环处理
由于汇编语言缺少很多更高级语言的“语法糖”,很多场景下我们需要模拟一些高级语言的特性。
例如,在Javascript中的循环写法如下
for(let i =0; i <10; i++){// do something}
在汇编语言中,我们可以使用cmp指令进行比较,使用jmp指令进行跳转:
mov rcx, 0 ; initialize counter
loop_start:
cmp rcx, 10 ; compare counter to 10
jge loop_end ; jump to end if greater than or equal to 10
; do something
inc rcx ; increment counter
jmp loop_start ; jump to loop_start
loop_end: