100 likes | 255 Views
Conditional Statements. Topics if .. else For loop Do loop While loop. C code to Pseudo-C. C allows “ goto ” as means of transferring control Closer to machine-level programming style Generally considered bad coding style But, suitable for assembly programming. int max(int x, int y){
E N D
Conditional Statements • Topics • if .. else • For loop • Do loop • While loop
C code to Pseudo-C • C allows “goto” as means of transferring control • Closer to machine-level programming style • Generally considered bad coding style • But, suitable for assembly programming
int max(int x, int y){ if (x > y) return x; else return y; } if (t) then-statement; else else-statement; t = test_expr; if (!t) goto false; do then-statement; goto done; false: do else-statement; done: int goto_max(int x, int y){ int rval = y; int ok = (x <= y); if (ok) goto done; rval = x; done: return rval; }
Branch Instructions • b (unconditional) • Conditional • beq, bne • bgez, bgtz, blez, bltz • bgezal bltzal • Set Condition • Sltz
Conditional Branch Example int max(int x, int y) { if (x > y) return x; else return y; } # x in $a0, y in $a1 # return value in $t0 max: ble $a0, $a1, else or $t0, $a0, $0 jr $ra else: or $t0, $a1, $0 jr $ra t = test_expr; if (!t) goto false; do then-statement; goto done; false: do else-statement; done:
C constructs broken into ‘goto’ • Example – Add an array • Pseudo Code – with ‘goto’ • More explicit in control of flow • Directly translated into Assembly code sum = 0; for (i=0; i<N; i++) sum += A[i]; printf(“Sum of array A is, %4d”,sum); sum = 0; i = 0; Rept: if (i >= N) goto Done sum += A[i]; i++; goto Rept Done: printf(“Sum of array A is, %4d”,sum);
sum = 0; i = 0; Rept: sum += A[i]; i++; if (i < N) goto Rept printf(“Sum of array A is, %4d”,sum); .data A: .word 5:20 # 20-element array of initial values of 5 .text .globl main main: li $t0, 0 # $t0 <- sum li $a0, 0 # $a0 <- array index li $t9, 80 # array index upper bound in C context rept: lw $t2, A($a0) # $t2 <- value in the array add $t0, $t0, $t2 # sum += A[i] addi $a0, $a0, 4 # i++ in bytes blt $a0, $t9, rept ….
Int lin_search(char x){ i=0; Retval = -1; while (i<72){ if (Tabchar_i,0]==x){ retval = Tabchar[i,1]; break; } else i++; }; return retval; } Lin_search: # x in $a0 li $t0,0 li $v0, -1 lin_rept: bge done, $t0, 72 bne else, $a0, $s0 lw $v0, Tabchar[I,1] b done else: addi $t0, $t0, 1(??) b lin_rept done: jr $ra }
Initialize my own ‘free’ list struct node *list_init(int n) { struct node *free=NULL, *newp; for (i=0; i<n; i++) { newp=(struct node *) malloc(sizeof(struct node)); if (!newp) return NULL; else { newp->next = free; free = newp; } } return free; }
struct node *list_init(int n) { struct node *free=NULL, *newp; for (i=0; i<n; i++) { newp=(struct node *) malloc(sizeof(struct node)); if (!newp) return NULL; else { newp->next = free; free = newp; } } return free; }