Reputation: 181
I am experiencing some difficulties interpreting this exercise;
What does exactly xorl does in this assembly snippet?
C Code:
int i = 0;
if (i>=55)
i++;
else
i--;
Assembly
xorl ____ , %ebx
cmpl ____ , %ebx
Jel .L2
____ %ebx
.L2:
____ %ebx
.L3:
What's happening on the assembly part?
Upvotes: 7
Views: 17243
Reputation: 67
XORL is used to initialize a register to Zero, mostly used for the counter. The code from ccKep is correct, only that he incremented by a wrong value ie. 2 instead of 1. The correct version is therefore:
xorl %ebx , %ebx # i = 0
cmpl $54, %ebx # compare the two
jle .L2 #if (i <= 54) jump to .L2, otherwise continue with the next instruction (so if i>54... which equals >=55 like in your C code)
incl %ebx #i++
jmp .DONE # jump to exit position
.L2:
decl %ebx # <=54 (or <55
.DONE:
Upvotes: -1
Reputation: 182734
It's probably:
xorl %ebx, %ebx
This is a common idiom for zeroing a register on x86. This would correspond with i = 0
in the C code.
If you are curious "but why ?" the short answer is that the xor
instruction is fewer bytes than mov $0, %ebx
. The long answer includes other subtle reasons.
I am leaving out the rest of the exercise since there's nothing idiosyncratic left.
Upvotes: 19
Reputation: 5857
This is the completed and commented assembly equivalent to your C code:
xorl %ebx , %ebx ; i = 0
cmpl $54, %ebx
jle .L2 ; if (i <= 54) jump to .L2, otherwise continue with the next instruction (so if i>54... which equals >=55 like in your C code)
addl $2, %ebx ; >54 (or: >=55)
.L2:
decl %ebx ; <=54 (or <55, the else-branch of your if) Note: This code also gets executed if i >= 55, hence why we need +2 above so we only get +1 total
.L3:
So, these are the (arithmetic) instructions that get executed for all numbers >=55:
addl $2, %ebx
decl %ebx
So for numbers >=55, this is equal to incrementing. The following (arithmetic) instructions get executed for numbers <55:
decl %ebx
We jump over the addl $2, %ebx
instruction, so for numbers <55 this is equal to decrementing.
In case you're not allowed to type addl $2,
(since it's not just the instruction but also an argument) into a single blank there's probably an error in the asm code you've been given (missing a jump between line 4 and 5 to .L3
).
Also note that jel
is clearly a typo for jle
in the question.
Upvotes: 2