A conditional is a type of control flow that branches based on one or more expressions.
int a;
scanf("%d", &a);
if (a % 2 == 0) {
printf("%d is even", a);
} else {
printf("%d is odd", a);
}
Example of a conditional statement that checks whether a number is even or odd
At the assembly level, conditionals are implemented using jumps as well as logic for the condition. The compiler translates the boolean expression of the condition into arithmetic ones depending on the architecture.
<init>
'conditional setup
goto then if <condition>
else:
'alternative body
goto end_if
then:
'consequent body
end_if:
Given the C code:
int a = 5;
int b = 2;
if (a > b) {
// consequent
} else {
// alternative
}
write an equivalent conditional in assembly
.pos 0x1000
# <init>
ld $a, r0 # r0 = &a
ld (r0), r0 # r0 = a
ld $b, r1 # r1 = &b
ld (r1), r1 # r1 = b
mv r1, r2 # r2 = b
not r2 # r2 = !b
inc r2 # r2 = -b
add r0, r2 # r2 = a-b
bgt r2, then # a-b > 0 => goto then
else:
# alternative
br end_if
then:
# consequent
end_if:
.pos 0x2000
a: .long 5
b: .long 2