Now, let's try to understand how the if/else statement is translated to assembly language. Let's take an example of the following C code:
if (x == 0) {
x = 5;
}
else {
x = 1;
}
In the preceding code, try to determine under what circumstances the jump would be taken (control would be transferred). There are two circumstances: the jump will be taken to the else block if the x is not equal to 0, or, if x is equal to 0 (if x == 0), then after the execution of x=5 (the end of the if block), a jump will be taken to bypass the else block, to execute the code after the else block.
The following is the assembly translation of the C program; notice that in the first line, the value of x is compared with 0, and the jump (conditional jump) will be taken to the else block if the x is not equal to 0 (the condition was reversed, as mentioned previously). Before the else block, notice the unconditional jump to end. This jump ensures that if x is equal to 0, after executing the code inside of the if block, the else block is skipped and the control reaches the end:
cmp dword ptr [x], 0
jne else
mov dword ptr [x], 5
jmp end
else:
mov dword ptr [x], 1
end: