You are on page 1of 23

Lecture 6: Control Flow

Marriette Katarahweire

CSC 3112: Principles of Programming Languages 1/23


Introduction

The issue of control flow or ordering in program execution


Ordering is fundamental to most (though not all) models of
computing.
It determines what should be done first, what second, and so
forth, to accomplish some desired task.

CSC 3112: Principles of Programming Languages 2/23


Design issues for arithmetic expressions

What are the operator precedence rules?


What are the operator associativity rules?
What is the order of operand evaluation?
Are there restrictions on operand evaluation side effects?
Does the language allow user-defined operator overloading?
What mode mixing is allowed in expressions?

CSC 3112: Principles of Programming Languages 3/23


Expression Evaluation
The language mechanisms used to specify ordering are in eight
principal categories:
Sequencing
Selection
Iteration
Procedural abstraction: subroutines encapsulate collections of
statements and subroutine calls can be treated as single
statements
Recursion: subroutines which call themselves directly or
indirectly to solve a problem, where the problem is typically
defined in terms of simpler versions of itself
Concurrency: two or more program fragments executed in
parallel, either on separate processors or interleaved on a
single processor
Nondeterminacy: the execution order among alternative
constructs is deliberately left unspecified, indicating that any
alternative will lead to a correct result
CSC 3112: Principles of Programming Languages 4/23
Expression Evaluation

An expression consists of either a simple object (e.g., a literal


constant, or a named variable or constant) or an operator or
function applied to a collection of operands or arguments,
each of which in turn is an expression
use the term operator for built-in functions that use special,
simple syntax,
use the term operand for an argument of an operator
some languages define their operators as syntactic sugar for
more “normal”-looking functions. In Ada, for example, a + b
is short for ” + ”(a, b); in C++, a + b is short for
a.operator + (b)

CSC 3112: Principles of Programming Languages 5/23


Expression Evaluation

a language may specify that function calls (operator


invocations) employ prefix, infix, or postfix notation.
These terms indicate, respectively, whether the function name
appears before, among, or after its several arguments:
prefix: op a b or op (a, b) or (op a b)
infix: a op b
postfix: a b op
Postfix notation: used in the post-increment and decrement
operators (+ + and − −) of C and its descendants

CSC 3112: Principles of Programming Languages 6/23


Expression Evaluation
Most imperative languages use infix notation for binary
operators and prefix notation for unary operators and (with
parentheses around the arguments) other functions.
Lisp uses prefix notation for all functions, but with the third of
the variants above: in what is known as Cambridge Polish
notation, it places the function name inside the parentheses:
(* ( + 1 3) 2) ;
that would be (1 + 3) ∗ 2 in infix
(append a b c my_list)
Smalltalk uses infix notation for all functions (which it calls
messages), both built-in and user-defined
myBox displayOn: myScreen at: 100@50
Algol
a := if b <> 0 then a/b else 0;
The equivalent operator in C is written ...?... : ...
a = b != 0 ? a/b : 0;
CSC 3112: Principles of Programming Languages 7/23
Precedence and Associativity
When written in infix notation,without parentheses, the rich
set of built-in arithmetic and logical operators lead to
ambiguity as to what is an operand of what
In any given language, the choice among alternative
evaluation orders depends on the precedence and associativity
of operators
Issues of precedence and associativity do not arise in prefix or
postfix notation.
In Fortran, for example, which uses ∗∗ for exponentiation,
how should we parse a + b ∗ c ∗ ∗d ∗ ∗e/f ?

((((a + b) * c)**d)**e)/f
or
a + (((b * c)**d)**(e/f))
or
a + ((b * (c**(d**e)))/f)
CSC 3112: Principles of Programming Languages 8/23
Operator Precedence

The operator precedence rules for expression evaluation define


the order in which ”adjacent” operators of different
precedence levels are evaluated (”adjacent” means they are
separated by at most one operand)
Precedence rules specify that certain operators, in the absence
of parentheses, group ”more tightly” than other operators.
In most languages multiplication and division group more
tightly than addition and subtraction, so

2+3∗4

is 14 and not 20
Lesson: when unsure, use parentheses!

CSC 3112: Principles of Programming Languages 9/23


Precedence

Figure: Operator precedence levels in Fortran, Pascal, C, and Ada. The


CSC 3112: Principles of Programming Languages 10/23
Associativity

Associativity rules specify whether sequences of operators of


equal precedence group to the right or to the left.
The basic arithmetic operators almost always associate
left-to-right, so 9 − 3 − 2 is 4 and not 8
In Fortran, the exponentiation operator (∗∗) follows standard
mathematical convention, and associates right-to-left, so
4 ∗ ∗3 ∗ ∗2 is 262144 and not 4096.
In Ada, exponentiation does not associate: one must write
either (4 ∗ ∗3) ∗ ∗2 or 4 ∗ ∗(3 ∗ ∗2);

CSC 3112: Principles of Programming Languages 11/23


Variables as values vs. variables as references

Value model: A variable contains a value.


Reference model: A variable refers to an object with a value.
value-oriented languages: C, Pascal, Ada
reference-oriented languages: most functional languages (Lisp,
Scheme, ML), Clu, Smalltalk
Algol-68 kinda halfway in-between
Java deliberately in-between: built-in types are values,
user-defined types are objects - references

CSC 3112: Principles of Programming Languages 12/23


Variables as values vs. variables as references

Figure: The value (left) and reference (right) models of variables

CSC 3112: Principles of Programming Languages 13/23


Structured and Unstructured Flow Control

Unstructured control flow:


the use of goto statements and statement labels to implement
control flow
if (A .lt. B) goto 10 ! //".lt." means "<"
...
10 //statement label
Generally considered bad
Most can be replaced with structures with some exceptions
Break from a nested loop (e.g. with an exception condition)
Return from multiple routine calls
Java has no goto statement (supports labeled loops and
breaks)

CSC 3112: Principles of Programming Languages 14/23


Structured and Unstructured Flow Control

Structured control flow:


Statement sequencing
Selection with ”if-then-else” statements and ”switch”
statements
Iteration with ”for” and ”while” loop statements
Subroutine calls (including recursion)

CSC 3112: Principles of Programming Languages 15/23


Sequencing

the execution of statements and evaluation of expressions is


usually in the order in which they appear in a program text
specifies a linear ordering on statements, in a top-down order
one statement follows another
very imperative, Von-Neumann

CSC 3112: Principles of Programming Languages 16/23


Selection

selection (alternation): a run-time condition determines the


choice among two or more statements or expressions
sequential if statements

if ... then ... else


if ... then ... elsif ... else
(cond
(C1) (E1)
(C2) (E2)
...
(Cn) (En)
(T) (Et)
)

CSC 3112: Principles of Programming Languages 17/23


Selection
Case/switch statements are different from if-then-else
statements in that an expression can be tested against
multiple constants to select statement(s) in one of the arms of
the case statement:
A break is necessary to transfer control at the end of an arm
to the end of the switch statement
Most programming languages support a switch-like statement,
but do not require the use of a break in each arm
A switch statement can much more efficient compared to
nested if-then-else statements
C, C++, and Java:
switch (<expr>) {
case <const>: <statements> break;
case <const>: <statements> break;
...
default: <statements>
}
CSC 3112: Principles of Programming Languages 18/23
Iteration

Iteration: a statement is repeated a number of times or until a


run-time condition is met
Enumeration-controlled loops repeat a collection of
statements a number of times, where in each iteration a loop
index variable takes the next value of a set of values specified
at the beginning of the loop
Logically-controlled loops repeat a collection of statements
until some Boolean condition changes value in the loop
Pretest loops test condition at the begin of each iteration -
while loop in C/C++
Posttest loops test condition at the end of each iteration - Do
while loop in C/C++
Midtest loops allow structured exits from within loop with exit
conditions for (. . . ). . . ; if (. . . )break; . . . in C/C++

CSC 3112: Principles of Programming Languages 19/23


Recursion

Recursion: subroutines that call themselves directly or


indirectly (mutual recursion)
Typically used to solve a problem that is defined in terms of
simpler versions, for example:
To compute the length of a list, remove the first element,
calculate the length of the remaining list in n, and return n+1
Termination condition: if the list is empty, return 0
Iteration and recursion are equally powerful in theoretical sense
Iteration can be expressed by recursion and vice versa
Recursion is more elegant to use to solve a problem that is
naturally recursively defined, such as a tree traversal algorithm
Recursion can be less efficient, but most compilers for
functional languages are often able to replace it with iterations

CSC 3112: Principles of Programming Languages 20/23


Recursion - Factorial

int number = 5; //It is the number to calculate factorial


for(i = 1; i <= number; i++){
fact = fact * i;
}
System.out.println("Factorial of "+number+" is: "+fact);

CSC 3112: Principles of Programming Languages 21/23


Tail Recursion

No computation follows recursive call

int gcd (int a, int b) {


if (a == b) return a;
else if (a > b) return gcd (a - b,b);
else return gcd (a, b - a);
}

CSC 3112: Principles of Programming Languages 22/23


Errors in Expressions

Caused by:
Inherent limitations of arithmetic e.g. division by zero
Limitations of computer arithmetic e.g. overflow

CSC 3112: Principles of Programming Languages 23/23

You might also like