CMPUT 229 - Computer Organization and Architecture I

If/Else Conditional

229 RISC-V Examples - If/Else Conditional

This page builds upon 03a and introduces an else block to an if-statement.

Recall that if conditional with an else-block looks as follows in C/C++:

if (condition) {
    code statement(s)
} else {
    other code statements(s)
}

Similar to 03a, the assembly code uses the negation of the condition in the C/C++ code to skip to the else block.

foo:
    # Before if/else

    bne   t0, t1, _f2Else     # Example comparison, seeing if t0 == t1

    # "Then" block

    j     _f2Join    # Join the two blocks of code
_f2Else:

    # "Else" block

    j     _f2Join    # Join the two blocks of code
_f2Join:

    # After if/else conditional
    # ...

    jalr  zero, ra, 0

Here is a C code example for a complete if-then-else statement:

if(T >= 0) {
    ptr = string;
}
else {
    ptr = 0;
}
ptr++;

A typical RISC-V implementation for this statement is:

    blt  t0, zero, _else    # if T < 0 goto _else
    add  t1, t2, zero       # ptr <- string
    j    _join              # goto _join
_else:
    add  t1, zero, zero     # ptr <- 0
_join:
    addi t1, t1, 1          # ptr++

In this code, T is in register t0, ptr is in t1, string is in t2. The blt instruction stands for "branch less than" and the condition is true when T < 0 --- the negation of the condition in the original C code. At the end of the code block corresponding to the then part of the if statement, the jump instruction j is required to ensure that the execution skips the else block. The execution falls through from the else block to the addi statement that is at the point where the two diverging control paths join together again.

Link to a file containing the above code snippet