
Lectures 4-5 Imperative languages Iztok Savnik, FAMNIT March, 2020. 1 Literature • John Mitchell, Concepts in Programming Languages, Cambridge Univ Press, 2003 (Chapters 5 and 8) • Michael L. Scott, Programming Language Pragmatics (3rd ed.), Elsevier, 2009 (Chapters 6 and 8) • Lecture by Jan Karabaš, Concepts of imperative programming, Programming II, FAMNIT, 2015 • Iztok Savnik, Koncepti programskih jezikov, Skripta (in Slovene), FAMNIT, 2013 (Chapter 4) Imperative languages • Functional programming – Program is a function – Outcome is done by the evaluation of the function – Does not matter how the result is produced • Imperative programming – Program is sequence of instructions (states of the machine) – Outcome is build in the execution of instructions – Instruction changes the contents of main memory Functional vs. imperative approach • Two abstract computation models – Functional – Imperative • Functional programming – λ-calculus, recursively-enumerable functions – Abstract machine (program) is represented by a λ- term, the outcome is obtained by its reduction • Imperative programming – The abstract machine is a Turing machine (finite state automaton), – The outcome is obtained when the final state is reached Example Let us compute the greatest common divisor of two integers C++ OCaml int gcd(int x, int y) { x = abs(x); y=abs(y); let rec gcd x y = while (y != 0) { if y = 0 then x int t = x % y; else gcd y (x mod y);; x = y; y = t; } Functional: values, recursion return x; Imperative: variables, loop, sequence } Imperative programming • Machine has read-write memory for storing variables • (Turing) machine consists of the states and instructions, which define computations and transitions between states • Execution means the changes of states of the machine rather than the evaluation (reduction) • The (way of) transitions are shaped (controlled) by the values of variables • Execution of instruction can change the values of variables - side-effects Structured control • Structured and unstructured control flow – Unstructured: goto statements – Structured: syntactical constructs direct computation • Structured programming, 1970 – »Revolution« in software engineering – Top-down design (i.e., progressive refinement) – Modularization of code – Structured types (records, sets, pointers multidimensional arrays) – Descriptive variable and constant names – Extensive commenting conventions Structured control • Most structured programming ideas were implemented in imperative languages – Pascal, C, Modula, Ada, Oberon, ... • Most of modern algorithms can be elegantly expressed in imperative languages Concepts of imperative languages • Read-write memory, variables • Instructions and sequences of instructions • Blocks • Conditional statements • Loops - conditional loops, iterations through ranges or through containers • Procedures and functions Program memory Variables • Memory of a program is organised into memory cells • Any cell can be accessed via its address; an integer, usually in range 0 – (262 − 1) • Variable is a symbolic name for a memory space of given size, which can be accessed by using the name instead of the address of the memory cell • Every program has symbol table, which stores the information about variables – Every record consists of: name (identifier), the address of the beginning of memory space, the size of allocated memory – Table changes during the execution of the program. Operations with variables • Program must allocate the memory space before the variable is used • The allocation can be either static or dynamic • Program reads the contents of the memory in the moment we refer to the identifier (name) • The contents of the memory referred by a variable is changed by assignment • The variable is freed either on the end of execution or on demand • Possible problems: – read/write to unallocated memory, concurrent write, memory leak. Models of variables • Value model of variables – Variable is a named container for a value – C, Pascal, Ada, ... • Reference model of variables – Named reference to a value – Algol 68, Clu, Lisp/Scheme, ML, Haskell, and Smalltalk – Reference model is not more expensive • Use multiple copies of immutable objects • The same performance as the value model Variables in C • Two important operators – Operator »&«: returns address of variable – Operator »*«: returns value of valiable at given address Value model int x = 1, y = 2, z = 3; x 1 int *ip; ip = &x; y 2 y = *ip; Symbol table RAM z 3 *ip = 0; *ip = *ip + 10; ip x 1 y = *ip + 1; y 2 z 3 *ip += 1; ip ++*ip; (*ip)++; Two important operators – Operator »&«: returns address of variable – Operator »*«: returns value of valiable at given address swap(&a, &b); ... a: void swap(int *px, int *py) { int temp; b: /* interchange *px and *py */ temp = *px; *px = *py; *py = temp; } Pointers and arrays in C • C has pointer arithmetic int a[10]; // a[0], a[1],..., a[9] pa = &a[0]; /* strlen: return length of string s */ int strlen(char *s) { int n; for (n = 0; *s != '\0', s++) n++; return n; } Variables in OCaml type ’a ref = {mutable contents:’a} • OCaml has weaker, but safer model of a variable – They are realised as the values of special reference type – Reference is initialised on creation by the referenced value – Memory space is automatically allocated using the type of referenced value – Function cannot be referenced – Assignment is a special function with resulting type unit – Reading has the type of the referenced variable – We do not have full access to the program’s memory – no pointers, no pointer arithmetics • Variables are similar to reference concept in C++ Example # let x = ref 2 ;; (* declaration and allocation val x : int ref = {contents=2} # !x;; (* reading, notice operator ‘!‘ - : int = 2 # x ;; (* reading of the reference - : int ref = {contents=2} # x := 5;; (* assignment - : unit = () # !x;; - : int = 5 # x := !x * !x;; (* reading, operation, and assignment - : unit = () # !x;; - : int = 25 Sequential control Sequential control is one of the basic principles of imperative programming languages 1. Sequences 2. Blocks 3. Condition statements 4. Loops Sequence • Sequence is foundamental abstraction used to describe algorithms – Instruction cycle of Von Neumann model LOOP: execute *PC; // execute instruction referenced by PC PC++; // increment programm counter (PC) by 1 goto LOOP; // loop • Sequence of instructions change the state of variables (memory) int t = x % y; x = y; y = t; let t = ref 0 let x = ref 42 Sequences in OCaml let y = ref 28 in t:= x mod y; x:=!y; y:=!x ;; • Syntax of OCaml sequences <expr1>; <expr2>; <expr3> (* list of expressions *) • Every expression in a OCaml sequence must be of type unit. # print_int 1; 2; 3;; Warning 10: this expression should have type unit. 1- : int = 3 # print_int 2; ignore 4; 6;; 2- : int = 6 Blocks • Imperative languages are typicaly block-structured languages • Block is a sequence of statements enclosed by some structural language form – Begin-end blocks, loop blocks, function body, etc. • Each block is represented using activation record – Includes parameters and local variables – Includes memory location for return value – Includes control pointers to be detailed in next lectures – Control pointers are used to control computation • Activation records are allocated on program stack Conditional statements • Machine languages use instructions for conditional jumps – Initial imperative approach • OCaml syntax if <cond_expr> then <expr_true> else <expr_false> ;; • Conditional statements is concept shared between imperative and functional languages – Both branches must agree on type in Ocaml – Conditional statement in Ocaml has value # (if 1 = 0 then 1 else 2) + 10;; - : int = 12 Loops – while-do • Repeat a block of commands while (or until) a condition is satisfied – Loop body changes the state of program • Statement while in OCaml while <cond_expr> do # let x = ref 42;; <sequence> val x : int ref = {contents = 42} done # let y = ref 28;; val y : int ref = {contents = 28} # let t = ref 0 in while !y != 0 do t := !x mod !y; x := !y; y := !t done;; - : unit = () # x;; - : int ref = {contents = 14} Loops – for statement • Statement for is classical construct of imperative prog. language # for i=1 to 10 do • Statement for in OCaml print_int i; print_string " " done; for <sym> = <exp1> to <exp2> do print_newline ();; <exp3> 1 2 3 4 5 6 7 8 9 10 done - : unit = () for <sym> = <exp1> downto <exp2> do # for i=10 downto 1 do <exp3> print_int i; done print_string " " done; print_newline () ;; 10 9 8 7 6 5 4 3 2 1 - : unit = () Loops – do-while statement • Loop condition is at the end of loop block do-while syntax /* itoa: convert n to characters in s */ void itoa(int n, char s[]) { do <sequence> int i, sign; while <cond_expr> if ((sign = n) < 0) /* record sign */ n = -n; /* make n positive */ • Statement i = 0; do { /* generate digits in reverse order */ repeat-until s[i++] = n % 10 + '0'; /* get next digit */ • Example: } while ((n /= 10) > 0); /* delete it */ if (sign < 0) s[i++] = '-'; s[i] = '\0'; reverse(s); } Loop control • Loop control in C programming language • Jumping out of loop – break • Jumping to loop condition – continue /* trim: remove trailing blanks, tabs, newlines */ for (i = 0; i < n; i++) int trim(char s[]) { if (a[i] < 0) int n; /* skip negative elements */ for (n = strlen(s)-1; n >= 0; n--) continue; if (s[n] != ' ' && s[n] != '\t' && s[n] != '\n') ... break; /* do positive elements */ s[n+1] = '\0'; return n; } Procedures and functions • Abstraction is a process by
Details
-
File Typepdf
-
Upload Time-
-
Content LanguagesEnglish
-
Upload UserAnonymous/Not logged-in
-
File Pages76 Page
-
File Size-