Lesson 05: C to Assembly
Assembly languages do not have control structures like if-else blocks, for-loops or while-loops. Instead, these can be built using branch instructions which are like goto statements that jump to a particular point in the program.
The simplest branch is done with the B instruction which always branches to its destination. The destinations are specified with labels which are just symbolic names inserted into the code.
We can make the branches depend in some condition. This is done with the CMP instruction which takes two arguments and compares them. It sets a "status register" in the processor which can be checked by a branch instruction. Or it can be done with the SUBS instruction which decreases the counter (register) value and update the result to the "status register", then control branches to the target label until counter value reaches the value zero. The following branches check the status register:
|Always take this branch
|Always take this branch
|Comparison equal or zero result
|Comparison not equal or non-zero result
|Result positive or zero
|Result minus or negative
|Arithmetic operation did not give carry-out (if C==0)
|Unsigned comparison gave lower (if C==0, same as BCC)
|Arithmetic operation gave carry-out
|Higher or Same
|Unsigned comparison gave higher or same (if C==1,same as BCS)
|Signed integer operation; no overflow occurred
|Signed integer operation; overflow occurred
|Signed integer comparison gave greater than (if Z==0 and N==V)
|Greater or Equal
|Signed integer comparison gave greater or equal (if N==V)
|Signed integer comparison gave less than (if N != V)
|Less or Equal
|Signed integer comparison gave less than or equal (if Z==1 or N!=V)
|Unsigned comparison gave higher (if C==1 and Z==0)
|Lower or Same
|Unsigned comparison gave lower or same (if C==0 or Z==1)
For instance, the following code snippet can be used for executing the <loop-body> 10 times.
Counting up in loop:
MOV R0, #0 ; initialize loop counted R0 Loop .... ; start of body of loop .... ADD R0, #1 ; increment loop counter CMP R0, #10 ; is it 10 yet? BLT LOOP ; branch if R0 < 10
Counting down in loop:
MOV R0, #10 ; initialize loop counted R0 Loop .... ; start of body of loop .... SUBS R0, #1 ; decrement loop counter and update "status" BNE Loop ; branch if R0 ≠ 0
An array is a sequence of items of the same kind in memoty. Arrays are a foundational data structure in almost every low level language. Every array has a base address, usually denoted by the name of the array, and contains N items. Each of these items has associated a growing index, ranging from 0 to N-1 (or 1 to N). Using the base address and the index we can access an item of the array.
In C language, when we declair an integer array A, ex. int A, actully, the variable A is a pointer that point to the address of the first element of array.