1 Control Flow: Expressions, Sequencing & Selection (Section 6.1- 6.4) A compilation of material developed by Felix Hernandez-Campos and Michael Scott.

Slides:



Advertisements
Similar presentations
ICE1341 Programming Languages Spring 2005 Lecture #13 Lecture #13 In-Young Ko iko.AT. icu.ac.kr iko.AT. icu.ac.kr Information and Communications University.
Advertisements

Intermediate Code Generation
Programming Languages and Paradigms
Adapted from Scott, Chapter 6:: Control Flow Programming Language Pragmatics Michael L. Scott.
CSCI 330: Programming Language Concepts Instructor: Pranava K. Jha Control Flow-II: Execution Order.
Control Structures Any mechanism that departs from straight-line execution: –Selection: if-statements –Multiway-selection: case statements –Unbounded iteration:
Expressions and Statements. 2 Contents Side effects: expressions and statements Expression notations Expression evaluation orders Conditional statements.
COP4020 Programming Languages Expression and assignment Prof. Xin Yuan.
Introduction to Programming Languages Nai-Wei Lin Department of Computer Science and Information Engineering National Chung Cheng University.
Programming Languages Marjan Sirjani 2 2. Language Design Issues Design to Run efficiently : early languages Easy to write correctly : new languages.
(8.1) COEN Control Structures  Control structure general issues  Compound statements  Selectors (conditional structures) – single – two-way –
1 Languages and Compilers (SProg og Oversættere) Sequence control and Subprogram Control.
Chapter 7Louden, Programming Languages1 Chapter 7 - Control I: Expressions and Statements "Control" is the general study of the semantics of execution.
Homework Any Questions?. Statements / Blocks, Section 3.1 An expression becomes a statement when it is followed by a semicolon x = 0; Braces are used.
UNIVERSITY OF SOUTH CAROLINA Department of Computer Science and Engineering CSCE 330 Programming Language Structures Chapter 7: Semantics Fall 2009 Marco.
Control Structures. Hierarchical Statement Structure Standard in imperative languages since Algol60. Exceptions: Early FORTRAN, COBOL, early BASIC, APL.
Chapter 8 . Sequence Control
ISBN Chapter 8 Statement-Level Control Structures.
CSE 452: Programming Languages Expressions and Control Flow.
Chapter 7 Expressions and Assignment Statements. Copyright © 2007 Addison-Wesley. All rights reserved. 1–2 Arithmetic Expressions Arithmetic evaluation.
1 Chapter 8 Statement-Level Control Structures In Chapter 7, the flow of control within expressions, which is governed by operator associativity and precedence.
Chapter 7Louden, Programming Languages1 Chapter 7 - Control I: Expressions and Statements "Control" is the general study of the semantics of execution.
1 Control Flow Aaron Bloomfield CS 415 Fall 2005.
CSE 425: Intro to Programming Languages and their Design A Few Key Ideas No particular language is a prerequisite for this course –However you should be.
1 Chapter 5: Names, Bindings and Scopes Lionel Williams Jr. and Victoria Yan CSci 210, Advanced Software Paradigms September 26, 2010.
1 Statement-Level Control Structures Levels of flow control Control Statements 1. Sequence 2. Selection 3. Iteration Unconditional branching Guarded commands.
CSC3315 (Spring 2009)1 CSC 3315 Programming Languages Hamid Harroud School of Science and Engineering, Akhawayn University
5-1 Chapter 5: Names, Bindings, Type Checking, and Scopes Variables The Concept of Binding Type Checking Strong Typing Type Compatibility Scope and Lifetime.
ISBN Chapter 7 Expressions and Assignment Statements.
Copyright © 2006 Addison-Wesley. All rights reserved.1-1 ICS 410: Programming Languages.
PLLab, NTHU,Cs2403 Programming Languages Expression and control structure Kun-Yuan Hsieh Programming Language Lab., NTHU.
1 Scope Rules (Section 3.3) CSCI 431 Programming Languages Fall 2003 A compilation of material developed by Felix Hernandez-Campos and Michael Scott.
Principle of Programming Lanugages 2: Imperative languages Isao Sasano Department of Information Science and Engineering ( structured programming, control.
Computer Science: A Structured Programming Approach Using C1 Objectives ❏ To be able to list and describe the six expression categories ❏ To understand.
Chapter 8 Chapter 8 Control Structures. Control Structures  A control structure is a control statement and the statements whose execution it controls.
CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 12.
ISBN Chapter 8 Statement-Level Control Structures.
sequence of execution of high-level statements
Expressions and Statements. Expressions Literals and identifiers are expressions More complex expressions are built from simple expressions by the application.
Programming Languages and Paradigms Imperative Programming.
Control Structures sequence of execution of high-level statements.
CSE 425: Control Flow I Categories of Control Flow Constructs Sequencing –order of expressions and statements Selection –if, else, switch Iteration –loops.
Expressions and Assignment Statements
8-1 Statement-Level Control Structures Introduction Selection Statements Iterative Statements Unconditional Branching Guarded Commands Conclusions.
Chapter 7 Expressions and Assignment Statements. Outline Introduction Arithmetic Expressions Overloaded Operators Type Conversions Assignment Statements.
Copyright © 1998 by Addison Wesley Longman, Inc. 1 Chapter 7 Levels of Control Flow: 1. Within expressions 2. Among program units 3. Among program statements.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
1 Iterative Statements Repeated execution of a (compound) statement by iteration or recursion –Iteration is statement level –Recursion is unit-level control.
1 Iteration and Recursion (Section 6.5 – 6.6) CSCI 431 Programming Languages Fall 2003 A compilation of material developed by Felix Hernandez-Campos and.
Statement Level Flow of Control GOTOs and Other Weirdness Copyright © by Curt Hill.
Slide 1 WEEK 8 Imperative Programming Original by Vitaly Shmatikov.
Principle of Programming Lanugages 3: Compilation of statements Statements in C Assertion Hoare logic Department of Information Science and Engineering.
1 Structure of Compilers Lexical Analyzer (scanner) Modified Source Program Parser Tokens Semantic Analysis Syntactic Structure Optimizer Code Generator.
Chapter 8 © 2002 by Addison Wesley Longman, Inc Introduction - Levels of Control Flow: 1. Within expressions 2. Among program units 3. Among program.
LECTURE 18 Control Flow. CONTROL FLOW Sequencing: the execution of statements and evaluation of expressions is usually in the order in which they appear.
W E E K F I V E Control Flow. Copyright © 2006 Addison-Wesley. All rights reserved.1-2 Chapter 8 Topics Introduction Selection Statements Iterative Statements.
Copyright © 2009 Elsevier Chapter 6:: Control Flow Programming Language Pragmatics Michael L. Scott.
Def: A control structure is a control statement and
Structure of Programming Language
Expressions and Assignment
8.1 Introduction - Levels of Control Flow: 1. Within expressions
Lecture 14: Iteration and Recursion (Section 6.5 – 6.6)
Chapter 8: Control Structures
Chap. 6 :: Control Flow Michael L. Scott.
Control Flow.
Control Flow Chapter 6.
Chap. 6 :: Control Flow Michael L. Scott.
Chapter8: Statement-Level Control Structures April 9, 2019
Chapter 8: Statement Level Control Structures
Controlling Program Flow
Presentation transcript:

1 Control Flow: Expressions, Sequencing & Selection (Section ) A compilation of material developed by Felix Hernandez-Campos and Michael Scott CSCI 431 Programming Languages Fall 2003

2 Control Flow Control flow refers to the order in which a program executesControl flow refers to the order in which a program executes This is fundamental in the imperative programming paradigmThis is fundamental in the imperative programming paradigm –E.g. Java, C++, Pascal, Fortran, Ada, etc. In other programming paradigms, the compilers or the interpreters take care of the orderingIn other programming paradigms, the compilers or the interpreters take care of the ordering –E.g. logic programming

3 Control Flow Mechanisms SequencingSequencing –Textual order, precedence and associativity in expression SelectionSelection IterationIteration Procedural abstractionProcedural abstraction RecursionRecursion ConcurrencyConcurrency NondeterminacyNondeterminacy

4 Expression Evaluation Expressions consist of operands (e.g. a variable) and operators or functions (e.g. +, abs())Expressions consist of operands (e.g. a variable) and operators or functions (e.g. +, abs()) –By definition, operators and functions return a value Operators are also functionsOperators are also functions –Infix notation is just syntactic sugar –In C++, a + b means a.operator+ (b)

5 Operators Operators are used inOperators are used in –Prefix notation »E.g. Expression (* (+ 1 3) 2) in Lisp –Infix notation »E.g. Expression (1 + 3) * 2 in Java –Postfix notation »E.g. Increment a++ in C Operators can have 1 or more operandsOperators can have 1 or more operands –Increment in C is a one-operand operator: a++ –Subtraction in C is a two-operand operator: a-b –Conditional expression in C is a three-operand operators: (a == 3 ? 0 : 1)

6 Operators Precedence and Associativity Precedence and associativity deal with the evaluation order within expressionsPrecedence and associativity deal with the evaluation order within expressions Precedence rules specify the order in which operators of different precedence level are evaluatedPrecedence rules specify the order in which operators of different precedence level are evaluated –* usually groups more tightly than + What is the results of 4 * 5 ** 6 ?What is the results of 4 * 5 ** 6 ?

7 Operator Precedence Precedence Table

8

9 Operators Associativity Associativity rules specify the order in which operators of the same precedence level are evaluatedAssociativity rules specify the order in which operators of the same precedence level are evaluated –+ is usually evaluated from left-to-right What is the results of 4 ** 5 ** 6 ?What is the results of 4 ** 5 ** 6 ? In Fortran, ** associates from right-to-left, as in MathIn Fortran, ** associates from right-to-left, as in Math In Ada, ** does not associate, so you have to write the previous expression as 4 ** (5 ** 6) to obtain the expected answerIn Ada, ** does not associate, so you have to write the previous expression as 4 ** (5 ** 6) to obtain the expected answer

10 Assignment The basic operation in imperative language is assignmentThe basic operation in imperative language is assignment –The side effect of this operation is a change in memory –Assignments affect the whole state of the program Purely functional language do not have assignmentPurely functional language do not have assignment –Side effects are not possible –Expression in purely functional languages depend only in their referencing environment Expressions produce valuesExpressions produce values Statements do not return values, but they have side effectsStatements do not return values, but they have side effects

11 Variables Value model of variablesValue model of variables –E.g. Pascal’s A := 3 –A is an l-value, and it denotes a position in memory –3 is a r-value, and it denotes a value with no explicit location Reference model of variablesReference model of variables –E.g. Java’s A = new Integer(3) –Variables are references to values

12 Variables Value and Reference model of variablesValue and Reference model of variables Variables in JavaVariables in Java – ariables.html ariables.htmlhttp://java.sun.com/docs/books/tutorial/java/nutsandbolts/v ariables.html

13 Expressions Other Issues Initialization may be implicit or explicit (at declaration or execution)Initialization may be implicit or explicit (at declaration or execution) –E.g. All variables have a default value in Perl, while Java requires all variables to be initialized »As a consequence, a simple typo in the name of variable in a Perl program may become a nasty bug Orthogonality means that features can be used in any combination and their meaning is consistent regardless of the surrounding featuresOrthogonality means that features can be used in any combination and their meaning is consistent regardless of the surrounding features –E.g. Assignment within conditional expressions in C++ –This is powerful but problematic, since typos may be legal »E.g. if (a==b) { … } and if (a = b) { … }

14 Expressions Other Issues Execution ordering within expressions is complicated by side effects (and code improvements)Execution ordering within expressions is complicated by side effects (and code improvements) –E.g. In Java, b = 1 int increment(int a) { b += 1; return a + 1; } c = (3 * b) * increment(b) –If the function call is evaluated before (3 * b) the final value of c is 12. If the product is evaluated before the function call, the value of c is 6. –But side effects within functions are a bad idea!

15 Expressions Other Issues Expressions may be executed using short-circuit evaluationExpressions may be executed using short-circuit evaluation –E.g. In C, p = my_list; while (p && p->key != val) p = p->next; »Field key is not accessed if the pointer p is null –This is not available in Pascal, so an additional variable is required (e.g. keep_searching ) p := my_list; while (p<>nil) and (p^.key <> val) do (*ouch*) p := p^.next »Access to key causes a run-time error at end of the search

16 Short-Circuited Conditions if ((A>B) and (C>D)) or (E<>F) then then-clauseelseelse-clause

17 Expressions Examples Expressions in JavaExpressions in Java – xpressions.html xpressions.htmlhttp://java.sun.com/docs/books/tutorial/java/nutsandbolts/e xpressions.html Regular Expressions in PerlRegular Expressions in Perl –Regular expressions in Perl Regular expressions in PerlRegular expressions in Perl

18 Unstructured Flow The GOTO Statement Control flow in assembly languages is achieved by means of conditional jumps and unconditional jumps (or branches)Control flow in assembly languages is achieved by means of conditional jumps and unconditional jumps (or branches) –E.g. JMP 30 … 30: ADD r1, #3 »30 is an assembly-level label –Higher level languages had similar statement: goto »E.g. In FORTRAN, If A.lt. B goto 10 … 10: … »10 is a statement label

19 Unstructured Flow The GOTO Statement Goto is considered evil since the 70sGoto is considered evil since the 70s –It potentially makes programs extremely convoluted »Spaghetti code »Code may be difficult to debug and even more difficult to read –In 1967, Dijkstra’s published an classic article, GoTo Considered Harmful, that pointed out the dangers of the goto statement in large programs »The larger the program, the worse the impact of goto statements

20 Structured Flow Structured flow eliminates gotoStructured flow eliminates goto –Nested constructs (blocks) provide the same expressive power Any program can be expressed using sequencing, selection and iterationAny program can be expressed using sequencing, selection and iteration –This was proved in a 1964 paper by Bohm & Jacopini However, there is a small number of cases in which unstructured flow is still more convenientHowever, there is a small number of cases in which unstructured flow is still more convenient –Modern structured languages like Java have addressed these cases in an structured manner

21 Structured Flow Special Cases Break and continueBreak and continue –Java’s branching statements » tml tmlhttp://java.sun.com/docs/books/tutorial/java/nutsandbolts/branch.h tml Early subroutine returnsEarly subroutine returns –Java’s return statements » tml tmlhttp://java.sun.com/docs/books/tutorial/java/nutsandbolts/branch.h tml Exceptions and ErrorsExceptions and Errors –Java’s exception handling » n.html n.htmlhttp://java.sun.com/docs/books/tutorial/java/nutsandbolts/exceptio n.html

22 Sequencing Sequencing is central to imperative programming languagesSequencing is central to imperative programming languages Sequencing of statements is usually defined by textual ordersSequencing of statements is usually defined by textual orders Enclosed sequences of statements are called compound statements or blocksEnclosed sequences of statements are called compound statements or blocks –E.g. begin … end, { … } –Declarations (e.g. variable types) may also be part of a code block

23 Selection If/Then/Else statementIf/Then/Else statement Case/Switch statementCase/Switch statement –The motivation for this statement is not purely esthetical –In some cases, switch statements are faster than nested if/then/else –The argument of the conditional must be a discrete value so that selection can be accomplished using an array indexed by the values (rather than checking the cases sequentially) The break statement in C/C++/Java makes code generation even more efficient in some caseThe break statement in C/C++/Java makes code generation even more efficient in some case

24 Selection Efficient Case/Switch Example Inefficient Code Generation

25 Selection Efficient Case/Switch Example Efficient Code Generation

26 Reading If interested in the history of programming, you can read these two classicsIf interested in the history of programming, you can read these two classics –Edsger Dijkstra, Goto Considered Harmful, CACM –C. Bohm and G. Jacopini. Flow diagrams, Turing machines and languages with only two formation rules. Communications of the ACM, 9(5): , May 1966.