11-Sequence Control (Expressions, Statements)
11-Sequence Control (Expressions, Statements)
December 7, 2020
1 Expressions
2 Statements
3 Program Units
+ - (a + b) * (c - d)
a b c d
Expression Syntax
Infix
Prefix
Postfix
(a + b) * (c - d)
3 + 4 * 5 = 23, not 35
If statement
if (count == 0)
average = 0;
else
average = sum / count;
Conditional Expression
average = (count == 0) ? 0 : sum / count;
C-based languages, Perl, JavaScript, Ruby
Polish Prefix: * + a b - c d
Cambridge Polish Prefix: (* (+ a b) (- c d))
Normal Prefix: *(+(a,b),-(c,d))
Derived from mathematical function f(x,y)
Parentheses and precedence is no required,
provided the -arity of operator is known
Mostly see in unary operators
LISP: (append a b c my_list)
Polish Postfix: a b + c d - *
Cambridge Polish Postfix: ((a b +) (c d -) *)
Normal Postfix: ((a,b)+,(c,d)-)*
Common usage: factorial operator (5!)
Used in intermediate code by some compilers
PostScript: (Hello World!) show
C program
int a = 5;
int fun1() {
a = 17;
return 3;
}
void main() {
a = a + fun1();
}
Eager evaluation
First evaluate all operands
Then operators
How about a == 0 ? b : b / a
Lazy evaluation
Pass the un-evaluated operands to the operator
Operator decide which operands are required
Much more expensive than eager
Lazy for conditional, eager for the rest
(a == 0) || (b/a > 2)
a := b ;
address? value?
5 5
Control statements
Selecting among alternative control flow paths
Causing the repeated execution of sequences of
statements
Control structure is a control statement and the
collection of its controlled statements
if control_expression
then clause
else clause
if (sum == 0)
if (count == 0)
result = 0;
else
result = 1;
Integer or character
- Single statement
case exp of - Block
1 : clause_A
2 , 7 : clause_B multiple values,
subrange
3 . . 5 : clause_C
1 0 : clause_D
else clause_E
end
for unrepresented values
expr_1
f o r ( expr_1 ; expr_2 ; expr_3 ) loop:
l o o p body if expr_2 = 0 goto out
[loop body]
expr_3
Can be infinite loop goto loop
out: ...
Forms Semantics
loop:
while (ctrl_expr) if ctrl_expr is false
loop body goto out
[loop body]
goto loop
out:...
do loop:
loop body [loop body]
while (ctrl_expr); if ctrl_expr goto loop
A r r a y L i s t a l = new A r r a y L i s t ( ) ;
...
Iterator i t = al . i t e r a t o r ( ) ;
while ( i t . hasNext ( ) ) {
O b j e c t element = i t . n e x t ( ) ;
...
}
to be continued
Expressions
Operator precedence and associativity
Side effects
Statements
Assignment
Selection Statement
Loop structures