Page 131 - ARM 64 Bit Assembly Language
P. 131
Structured programming 117
Listing 5.6 Complex selection in C.
1 static long a = 0x57;
2 static long b = 0x75;
3 static long c = 0x21;
4 static long x;
5 int main(void)
6 {
7 if((a<b)&&(a<c)){
8 x=a;
9 } else if ( b < c ) {
10 x=b;
11 } else {
12 x=c;
13 }
14 return 0;
15 }
5.2.3 Complex selection
More complex selection structures should be written with care. Listing 5.6 shows a fragment
of C code which compares the variables a, b,and c, and sets the variable x to the least of the
three values. In C, Boolean expressions use short circuit evaluation. For example, consider
the Boolean AND operator in the expression ((a<b)&&(a<c)). If the first sub-expression
evaluates to false, then the truth value of the complete expression can be immediately deter-
mined to be false, so the second sub-expression is not evaluated. This usually results in the
compiler generating very efficient assembly code. Good programmers can take advantage of
short-circuiting by checking array bounds early in a Boolean expression, and accessing array
elements later in the expression. For example, the expression ((i<15)&&(array[i]<0))
makes sure that the index i is less than 15 before attempting to access the array. If the index is
greater than 14, the array access will not take place. This prevents the program from attempt-
ing to access the sixteenth element on an array that has only fifteen elements.
Listing 5.7 shows an AArch64 assembly code fragment which is equivalent to Listing 5.6.In
this code fragment, x0 is used to store a temporary value for the variable y, and the value is
only stored to memory once, at the end of the fragment of code. The first if statement is im-
plemented using branch instructions. Its comparison is performed on line 17 of Listing 5.7.
If the comparison evaluates to false, then it immediately branches to the elseif block, but if
the first comparison evaluates to true, then it performs the second comparison in the if state-
ment. Again, if that comparison evaluates to false, then it branches to the elseif block. If
both comparisons evaluate to true, then it executes x0=a and then branches to the endif
label. In this case, x0 is already set to a, so it just branches to endif.