90 likes | 111 Views
CS 331, Principles of Programming Languages. Chapter 3. Structured Programming. Historical controversy over readability of computer programs Undisciplined use of the infamous “goto” statement can lead to programs that are impossible to follow
E N D
Structured Programming • Historical controversy over readability of computer programs • Undisciplined use of the infamous “goto” statement can lead to programs that are impossible to follow • Modern languages provide control structures that should make programs easier to read
Control Structures • Composition • <stmt>; <stmt> • Conditional • if <expr> then <stmt> else <stmt> • Iteration • while <expr> do <stmt>
Other Control Structures • Iteration (iterating at least once) • repeat <stmt> until <expr> • Definite Iteration • for <variable> = <expr> to <expr> do <stmt> • Multi-way selection • case <expr> of <label> : <stmt>; <label> <stmt> ;
Variations • In C (and C++) we have premature loop exit • break • continue • But composition, if, and while are basic • case can be simulated with nested if • repeat can be simulated with while and an extra boolean variable (how would that work?)
Invariants • Invariants are formal statements that describe the state of affairs at some point in your program • they should express your understanding of what’s going on in your program • Bugs live in those parts of your program that you don’t (yet) understand! • the C language assert macro does something like this, e.g. assert(ptr!=0);
Loop Invariants • A loop invariant is a logical statement that • is true before a loop starts, and • is true after the loop ends, • no matter how many times (0 or more) the loop is executed • To be useful, the loop invariant has to somehow capture the essense of what the loop is doing
Pseudo-code with invariants // see if a list of array elements is in ascending order Boolean testsorted (X[], int lower, int upper) assert ((X != 0) && (lower <= upper)) int I = lower // “is sorted” means that for any m,n in the given range, // m<n implies X[m] <= X[n] invariant (X[lower..I] is sorted) // loop invariant while (I < upper) do if X[I] > X[I+1] then the list isn’t sorted, return false I = I+1 invariant (X[lower..I] is still sorted) // so keep going end invariant (I == upper) and therefore X[lower..upper] is sorted return true
Functions and Invariants • Identify what a piece of code can assume • precondition • asserts at the top of a function can do this • and what it is supposed to do • postcondition • asserts at the end of a function (sanity check?) • and every few lines in between