Docstoc

Principles of Programming Languages

Document Sample
Principles of Programming Languages Powered By Docstoc
					  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
• Modern languages provide control
  structures that should make programs easier
  to read
              Control Structures
• Composition
  – s1; s2; s3
• Conditional
  – if e1 then s1 else s2
• Iteration
  – while e2 do s1
       Other Control Structures
• Iteration (iterating at least once)
   – repeat s3 until e3
• Definite Iteration
   – for
• Multi-way selection
   – case
                 Variations
• In 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);
      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 and lower <= upper)
(might we also assert that X[lower..upper] have been initialized?)
int I = lower
assert X[lower..I] is sorted N.B. true before and after loop
while I < upper do
         if X[I] > X[I+1] then the list isn’t sorted, return false
         I = I+1
         assert X[lower..I] is still sorted, so keep going
end
assert (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

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:14
posted:7/23/2012
language:English
pages:8