110 likes | 190 Views
Chapter 8 Exercises. Exercise 1:. Construct a new H1 assembler instruction with semantics:. retn x ; o <= x <= 255. pc = mem[sp++]; sp = sp + x;. Exercise 2:. Create the following H1 instruction: Use this instruction to implement the C++ code.
E N D
Exercise 1: • Construct a new H1 assembler instruction with semantics: retn x ; o <= x <= 255 pc = mem[sp++]; sp = sp + x;
Exercise 2: • Create the following H1 instruction: • Use this instruction to implement the C++ code cora ; ac = sp + ac; # cora (convert relative address) void foo () { int x = 6; int * p; p = &x cout << *p << endl; } int main() { foo(); }
Exercise 3: • Draw a picture of H1 memory upon completion of the line labeled (A) in the following program: #include <iostream> using namespace std; int x = 100; void fr(int &z) { z = z+ 5; // A } void ft(int &y) { y = y + 1; fr(y); } void main() { ft(x); cout << “x = “ << x << endl; }
Exercise 4: • In the Chapter 7 quiz I asked that you write the H1 assembler code that can execute a function be calling the address of the function as it is stored in another variable. • Prof Dos Reis suggested the following solution to this problem: foo: ... ; whatever code is appropriate for foo ret p: dw foo @call dw E000 ; opcode for call ;;; now we execute foo() ld p add @call ; construct “call *p” st *+1 ; place it in the line of execution exec: dw 0 ; execute it now ... ; rest of code
Exercise 4 (continued): • In C++ it is possible to define a pointer variable of type “function”. For example, ifis a function then the following is a variable, p, that can hold the address of this functionas in void foo() {...} void (*p)(); p = &f;
Exercise 4 (continued): • Draw the H1 memory configuration diagram as if this program were written in H1 and currently executing the line labeled (X). #include <iostream> using namespace std; void a() { cout << “A” << endl; } void b() { cout << “B” << endl; // (X) } void foo(void (*p)()) { p(); } int main () { foo(b); foo(a); }
Exercise 4 (continued): • Write the H1 program of the C++ program on the previous slide.
Exercise 5: • This is Problem 8.41. What is happening here? #include <iostream> using namespace std; int x = 1, y = 2; void f(int &x) { x = x+ 5; cout << x << endl; } int main() { f(x+y+5); cout << x << " " << y << endl; }
Exercise 6: • In C and C++ arrays do not “know” their own length. So when we pass an array to a function we also need to pass the “length” of the array meaning the number of entries in the array or the maximum index value that are currently in use. • Write an H1 assembler program that implements the following C++ function, creates a global array and then populates some but not all of its elements. // finds the index of the largest element in // arg1 in the index range [0,end], end >= 0. int getMaxIndex(int [] a, int end) { int temp = a[0], ndx = 0; for (int i = 1; i <= end; i++) { if (a[i] > temp) { ndx = i; temp = a[i]; } } return ndx; }
Title: • Write