6.5 If-Elseif-Else Statement

The following is a C code containing if-ElseIf-else statements:

if (x == 0) {
x = 5;
}
else if (x == 1) {
x = 6;
}
else {
x = 7;
}

From the preceding code, let's try to determine a situation when jumps (control transfers) will be taken. There are two conditional jump points; if x is not equal to 0, it will jump to the else_if block, and if x is not equal to 1 (a condition check in else if), then the jump is taken to else. There are also two unconditional jumps: inside the if block after x=5 (the end of the if block) and inside of the else if after x=6 (the end of the else if block). Both of these unconditional jumps skip the else statement to reach the end.

The following is the translated assembly language showing the conditional and unconditional jumps:

cmp dword ptr [ebp-4], 0
jnz else_if
mov dword ptr [ebp-4], 5
jmp short end

else_if:
cmp dword ptr [ebp-4], 1
jnz else
mov dword ptr [ebp-4], 6
jmp short end

else:
mov dword ptr [ebp-4], 7
end:
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.202.224