Control Flow: Principles of Programming Languages (CS213)
Control Flow: Principles of Programming Languages (CS213)
Control Flow: Principles of Programming Languages (CS213)
Prof. M. N. Sahoo
sahoom@nitrkl.ac.in
sahoo.manmath@gmail.com
Introduction
Control flow decides the order of
statement execution in a program.
4 ways to control
Sequencing
Unconditional Jump/ Branch
Selection/ Alternation
Iteration/ Loop
Sequencing
Principal means of controlling the
order in which side effects occur.
In most imperative programming
languages, sequencing comes
naturally.
But, few languages (e.g. LISP,
Scheme) provide special constructs
for sequencing.
3
Selection
10
11
Translated to
12
Switch Statements
Switch statements are a special case
of if/then/elsif/else.
Principal motivation: Generate
more efficient code.
13
Implementation of Switch
Statements(1)
14
Implementation of Switch
Statements(2)
15
Implementation of Switch
Statements(3)
16
Iteration
Enumeration-controlled loops
Example: for-loop in Modula-2 and Ada, do-loop in
Fortran
One iteration per element in a finite set.
The number of iterations is known in advance.
Fortran
do i = 1, 10, 2
...
Enddo
Modula-2
FOR i := first TO last BY step DO
...
END
18
(Target
Code-1)
Which
2
6
(Target Code2)
Code is better???
19
Generic translation
Pre-compute the number of iterations
20
Generic translation
Iteration count works well for +ve or
ve step.
However, if a loop body modifies the
index and/or end-of-loop bound
variable then, the no. of iterations
cant be pre-computed.
21
Issues
1. Can control enter or leave the loop in any way
other
than
through
the
enumeration
mechanism?
2. What happens if the loop body modifies
variables that were used to compute the endof-loop bound?
3. What happens if the loop body modifies the
index variable itself?
4. Can the program read the index variable after
the loop has completed, and if so, what will its
value be?
22
25
26
Logically Controlled
Loops
Pre-loop test
while ... do ...
Post-loop test
repeat ... until ...
do ... while ...
Loop is executed at least once.