Title: 159'331 Programming Languages
1159.331 Programming Languages Algorithms
- Lecture 8 - Imperative Programming Languages -
Part 4 - Flow of Control
2Flow of Control
- Imperative languages give the programmer control
over the order in which statements are executed
(or skipped) - we call this the flow of control - Mechanisms to support it are
- Sequencing (eg jumping around with gotos)
- Selection (if-then-else or switch-case etc)
- Repetition (for-loops, while-loops, repeat-until
etc) - Routine invocation (calling functions
procedures)
3Sequencing
- Sequencer says which statement must be executed
next - In absence of contrary information just execute
the next in the program text - We have constructs that allow us to jump
around - goto statement and labeled statements
- goto generally misused - leads to spaghetti
code - Some old languages had no other solution so
had to emulate some of the better structured
flow constructs using gotos) - It helps us use then sensibly if our labels
are textual and meaningful rather than just
numbers like in Fortran
4- In C
- goto my_label
-
- my_label
- In Ada
- goto My_Label
-
- ltltMy_labelgtgt
- The goto compiles down into a corresponding
program-counter jumping instruction, and can
therefore be thought of as a relic of the
machine code
- In Fortran
- GOTO 1010
-
-
- Opinions are still divided about the harm the
goto statement does in itself. - It is generally no longer needed in languages
that have more structured flow control
capabilities - maybe still useful for bail-out
or exception handling? Arguably an explicit
label gives you something to search for in the
program source code.
5Selection
- The if-statement causes one of two pieces of
code to be executed, depending upon the value of
a Boolean expression known as the condition. - Many languages allow lists of condition-action
pairs to be specified in an if-then-elseif-then-e
lse style construct - The switch or case statement is generallya
special sort of selection statement that compiles
down to arithmetically computed jumps in the
program counter
6(No Transcript)
7- switch/case syntax not awfully easy to read
- Language designers need to consider
- Can action be labelled with more than one choice
value (yes in both Ada and C) - Can action be labelled with a range of values
(Yes in Ada, No in C) - Restricted types in the switching expressions (
usually int for efficiency reasons - the choices
need to be evaluated at compile time) - What happens if a value occurs twice in list
(compile time error in both Ada and C) - What happens if the value is not in the choice
list (default action, or fall-through)
8Is this more elegant than the if-statement used
in figure 2.8 ?
Matter of style as to whether to use ifs or
switchs ?
9Routine Invocation
- It is natural to bundle a group of statements
together when they form a natural conceptual
unit - Encapsulate the code in a named procedure (or
subroutine) - Unlike the goto, these guarantee return of the
flow of control to the point of call when they
are over. - In C read_next_line()
- In Ada Read_Next_Line
- This idea (of calling named procedures) is
also a basis for abstraction
10Repetition
- Two main forms of repetition
- looping over a pre-calculated number of
iterations (for loop) - repeating over some condition (while loop )
- Arguably infinite-looping is a third, for
certain long running programs. (Can emulate with
a construct like while(true) ) - Controlled Exits from loops are also important -
use of break and continue ideas, replace need
for arbitrary gotos
11- Note the need for/use of a control variable i or
I - C syntax slightly bizarre! Three parts of
the for statement - initialisation 2) termination test 3) the
increment - C allows multiple initialisations separated
by a comma, and also allows us to declare I on
the fly inside ()s
12- Arguably the C for is really a while in
disguise as - The check is done after each repetition
- The increment operation is done after each
repetition - We can safely change the control variable
inside the loop (If we know what we are doing!) - Most language s associate a (known at the start
of the loop) range with the for statement
13Some Language Design for-questions
- Where should responsibility for declaring the
control variable lie? What is its scope? - In C it is a normal variable
- In Ada it is declared for you implicitly
- If the scope of the control variable (I) is
larger than the block of for-code, what should
its terminating value be? - In C its is the value upon which the test
failed - In Ada it is no longer in scope
14- How is the control variables type determined?
- In Ada the compiler derives the type from the
type of the given range (eg 1..10 ) - In C - more or less anything goes, although
standard idiomatic form is for use of an int - Can i be modified inside the loop (In Ada No, in
C yes) - Can the range be empty ( so the loop runs zero
times - Yes in both C and Ada - Can the range be modified inside the loop - No
in Ada, Yes in C
15- Old Fortran
- DO 1010, I1,10
-
- 1010 CONTINUE
- The integer values 1,10 are the start/stop
values, so I ranges 1,2,3,4,5,6,7,8,9,10 - The CONTINUE in Fortran is a do-nothing
statement - might compile to No-Op
- Modern Fortran
- do i1,10,2
-
- enddo
- The third value is the stride, so we get values
of I of 1, 3, 5, 7, 9 - But what does it mean if we change I inside the
loop? (Undefined)
16While
- While-statement - repetition continues an
indeterminate number of times as long as a
given condition is satisfied - In C while( ! end_of_file() )
- In Ada
- while not End_Of_File loop
-
- end loop
- Some languages allow the condition to go at the
end, in the the form of a repeat -until
statement (not in Ada) - C implements this in form of
- dowhile( expr )
17- Warning - the while-do is properly guarded and
can execute its loop code zero or more times. - The repeat-until executes its loop at least
once - Need to be aware of this if testing for some
condition such as end of file. - while has now made it into modern Fortran -
prior to this we had to emulate it using
gotos and labelled statements - break can be use d to exit from the innermost
containing loop - it abandons the loop - continue (in C) is used to go on to the next
iteration (or the innermost containing loop)
18Some languages provide an exit statement that
can exit from more than just the innermost loop.
(A much criticised feature!) In C and C
exit() is a system call to exit the program
and hand control back to the operating system -
ie it exists everything!
19Run-Time Error Handling
- Sometimes our conditionals, loops
break/continues are enough for the programmer to
anticipate error conditions. - Sometimes we need more controls to handle run
time errors - Three main causes for a program to get into
trouble - Domain/data errors (synchronous)
- Resource exhaustion (synchronous or
asynchronous) - Loss of facilities ( asynchronous)
- Worse still, errors can be
- Caused internally ( eg in overflow or running
out of memory) or externally (to the program) (eg
user interupts or power failure) - Reproducing or non-reproducing (intermittent)
-the worst sort!
20Domain/Data Errors
- When an operation is called with data value s
that cannot be handle d by that operation - Eg divide by zero, or integer overflow
- These are synchronous - they happen every time
the program is run with the same data - Programmer responsibility to anticipate these
- Sometimes easy (for simple types) but some
cases - eg testing for a singular matrix
prior to trying (impossibly) to invert it is
just as hard as inverting it.
21Resource Exhaustion
- Sometimes resources like memory, disk space or
exclusive use of video screen are explicit
requests - They can have failure return conditions o f
various sorts - eg NULL pointer return from
malloc() in C, or new in Ada just fails if
there is not enough memory to meet the request - Some requests are implicit - eg stack variables
and CPU-time granted to a process (try
declaring a very large local array in C) - Both are synchronous in that they are caused by
specific program actions but also asynchronous
in that they may not happen the next time the
program is run - (more memory available for
various reasons)
22Loss of Facilities
- All sorts of external things can occur
- Loss of power
- Failure of network connection
- Disk head crashes
- An open file is removed by some other program
- Some one else reboots your computer
- All these errors are asynchronous as they are
unrelated to any action of your program
23Signals
- Signals are a way for the programmer to
specify some error handling to try to anticipate
run-time problems. - Arguably this is straying into operating system
issues rather than programming language issues
but different languages do support these ideas
in various ways. - We group the various errors into named classes -
known as error conditions (eg Constraint Error in
Ada for any out of bounds result, or SIGFPE -
floating point error signal in UNIX/C - A signal statement names an error condition and a
procedure to be called if/when it occurs - These handler procedures are like
interruptions to the normal control flow in your
program.
24- In UNIX/C signal( SIGFPE, close_down )
- Tells the system to call your close_down()
procedure whenever a floating point operation
goes awry. - You are registering a handler to trap a
signal - Ada has facilities like
- Attach_Handler( Close_Down, Control_C_Hit )
- To say what you want done when the user
presses control-c during execution of your
program (its usually control-z on DOS, or some
sort of force-quit or kill-program in various
windowing systems) - This might be important to preserve data in a
database from corruption if your program is
interrupted
25- Signals can be easily implemented as a library
function for any language that lets you pass
names of (your) procedures as parameters to
(library) procedures - C and Ada do this.
- However signals are not a perfect solution
- What if you forget to make your handler
procedure properly exit the program and it
returns instead? - There is no way of getting access to local
variables and data from inside the handler so
it may not be able to do much
26Exceptions
- Are a more integrated solution to handling error
conditions - An exception handler consists of an error
condition and a (handling) set of statements - It can be attached to a block of statements
that have to be protected from the error
condition - If one of the statements in the protected
block fails with the specified error condition,
then the handler code is invoked.
27Statement m has caused the error condition
Arrows show the flow of control
28Ada has four (coarse) groupings of error
conditions Constraint_Error - values out of
bounds Program_Error - problems with flow of
control Storage_Error - memory and storage
issues Tasking_Error - errors from paralel
processes
29Because exception handling is more integrated
(than signals library code can be), we have
access to local data to analyse the circumstances
of the error condition.
We talk about raising an exception and exception
occurences or instances
30Java Exceptions
- try
- // block of protected code that might
- // throw an exception
- catch( ArrayIndexOutOfBoundsException e )
- // handler code used for array index out of
bounds - catch(SomeOtherException soe )
- // more handler code for some other
exceptions -
- finally
- // code that is always called
- // after ANY exception is caught
31Language Designer Exception Issues
- How are exceptions represented (ints in C, in
Ada as declared names, Java has its own class
hierarchy) - Can the programmer declare exceptions (C no, Ada
yes) - Can additional information be gained from eth
exception ( C No, Ada yes, Java yes) - What happens if an exception is not caught
(trapped) - in C program aborted, in Ada and Java
the exception propagates to the next
dynamically enclosing unit of code - (up the
call tree) - Can a handler cope with multiple exceptions?
(Yes in c, Java and Ada) - Can the programmer cause a given exception to
occur (yes in C, Ada and Java)
32Orthogonality of statements
- sort orthogonality implies that in any position
in which a statement is allowed, any statement is
allowed - Modern languages are in fact almost completely
orthogonal as to statements - Some restrictions in older languages
- Minor deviation is that Ada exception handlers
can only be attached to begin-end sequences of
code and not to single statements
33- number orthogonality implies that wherever one
statement is allowed, zero or more should be
allowed. - Relates to the syntax of the rest of the language
- Languages vary in their number orthogonality
- The more-than-one case is covered in Ada but in C
we generally need the extra s - The zero-case is covered by the null statement
which takes the form of a single semicolon in C
and has the form null in Ada.
34Imperative Part 4 - Summary
- Flow of Control
- Sequencing
- Selection
- Routine Invocation
- Repetition - Loops Exits
- Run Time Error Handling
- Domain/Data errors
- Resource Exhaustion
- Loss of Facilities
- Exceptions
- Orthogonality of Statements
- Bal Grune Chapter 2, Section 2.3
- Sebesta Chapter 8