Chapter 7 Control I Expressions and Statements

Similar documents
Programming Languages Third Edition. Chapter 9 Control I Expressions and Statements

Expressions and Statements. Department of CSE, MIT, Manipal

G Programming Languages - Fall 2012

UNIT 3

Chapter 7. - FORTRAN I control statements were based directly on IBM 704 hardware

Lecture 9: Control Flow

CSc 520 Principles of Programming Languages. 26 : Control Structures Introduction

Control Structures. Outline. In Text: Chapter 8. Control structures Selection. Iteration. Gotos Guarded statements. One-way Two-way Multi-way

More Examples. Lecture 24: More Scala. Higher-Order Functions. Control Structures

9/21/17. Outline. Expression Evaluation and Control Flow. Arithmetic Expressions. Operators. Operators. Notation & Placement

Ch. 7: Control Structures

Programming Languages Third Edition. Chapter 7 Basic Semantics

Chapter 8 Statement-Level Control Structures

CSE 3302 Programming Languages Lecture 5: Control

COP4020 Programming Languages. Control Flow Prof. Robert van Engelen

Chapter 8. Statement-Level Control Structures

Iterators. Lecture 24: Iterators & Exceptions. Implementing Iterators. When Good Programs Go Bad! - where! Abstract over control structures (in Clu)!

Chapter 8. Statement-Level Control Structures

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Page # Expression Evaluation: Outline. CSCI: 4500/6500 Programming Languages. Expression Evaluation: Precedence

3. Java - Language Constructs I

The PCAT Programming Language Reference Manual

LECTURE 17. Expressions and Assignment

Control Flow February 9, Lecture 7

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

LECTURE 18. Control Flow

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Flow of Control Execution Sequence

Chapter 8. Statement-Level Control Structures

Programming for Engineers Iteration

CPSC 3740 Programming Languages University of Lethbridge. Control Structures

! Non-determinacy (unspecified order) Maria Hybinette, UGA 2. 1 Landin adding sugar to a language to make it easier to read (for humans)

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Statement level control structures

Chapter 6 Control Flow. June 9, 2015

Iteration. Side effects

Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler Front-End

2/20/2018. Chapter 6:: Control Flow. control flow or ordering. basic categories for control flow (cont.): basic categories for control flow:

Iterative Statements. Iterative Statements: Examples. Counter-Controlled Loops. ICOM 4036 Programming Languages Statement-Level Control Structure

Lambda Calculus. Gunnar Gotshalks LC-1

Attributes, Bindings, and Semantic Functions Declarations, Blocks, Scope, and the Symbol Table Name Resolution and Overloading Allocation, Lifetimes,

Test 1 Summer 2014 Multiple Choice. Write your answer to the LEFT of each problem. 5 points each 1. Preprocessor macros are associated with: A. C B.

14. Exception Handling

1 Lexical Considerations

Concurrency. Lecture 14: Concurrency & exceptions. Why concurrent subprograms? Processes and threads. Design Issues for Concurrency.

Languages and Compilers (SProg og Oversættere)

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Chapter 8. Statement-Level Control Structures ISBN

PROCEDURAL DATABASE PROGRAMMING ( PL/SQL AND T-SQL)

CSE 452: Programming Languages. Outline of Today s Lecture. Expressions. Expressions and Control Flow

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

The role of semantic analysis in a compiler

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode

Lexical Considerations

Casting -Allows a narrowing assignment by asking the Java compiler to "trust us"

Flow Control. CSC215 Lecture

Repetition Structures

Control in Sequential Languages

The SPL Programming Language Reference Manual

Review of the C Programming Language

Language Fundamentals Summary

Review of the C Programming Language for Principles of Operating Systems

COP4020 Fall 2006 Final Exam

Semantic Analysis. How to Ensure Type-Safety. What Are Types? Static vs. Dynamic Typing. Type Checking. Last time: CS412/CS413

This book is licensed under a Creative Commons Attribution 3.0 License

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and

The Arithmetic Operators

Concepts Introduced in Chapter 7

Lexical Considerations

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

Expression Evaluation and Control Flow. Outline

Topics Covered Thus Far. CMSC 330: Organization of Programming Languages. Language Features Covered Thus Far. Programming Languages Revisited

Chapter 1. Fundamentals of Higher Order Programming

Programming Language Concepts Control Flow. Janyl Jumadinova 2 February, 2017

Software II: Principles of Programming Languages. Why Expressions?

Ordering Within Expressions. Control Flow. Side-effects. Side-effects. Order of Evaluation. Misbehaving Floating-Point Numbers.

Control Flow COMS W4115. Prof. Stephen A. Edwards Fall 2006 Columbia University Department of Computer Science

NOTE: Answer ANY FOUR of the following 6 sections:

CSE 307: Principles of Programming Languages

Chapter 7. Expressions and Assignment Statements ISBN

Chapter 14. Exception Handling and Event Handling

Chapter 7. Expressions and Assignment Statements

Flow of Control. Flow of control The order in which statements are executed. Transfer of control

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

V2 2/4/ Ch Programming in C. Flow of Control. Flow of Control. Flow of control The order in which statements are executed

A Short Summary of Javali

CS558 Programming Languages

Topic IV. Block-structured procedural languages Algol and Pascal. References:

Introduction to Programming Using Java (98-388)

Lecture 19: Functions, Types and Data Structures in Haskell

Concepts Introduced in Chapter 6

Informal Semantics of Data. semantic specification names (identifiers) attributes binding declarations scope rules visibility

Accelerating Information Technology Innovation

Instructor: SIR MUHAMMAD NAVEED Created by: ARSLAN AHMED SHAAD ( ) MUHAMMAD BILAL ( ) ISIT:

G Programming Languages - Fall 2012

Unit 3. Operators. School of Science and Technology INTRODUCTION

C++ Programming: From Problem Analysis to Program Design, Third Edition

Exception Handling: Control. Exception handling is the control of error conditions or other unusual events during the execution of a program.

Intermediate Code Generation

Topic IV. Parameters. Chapter 5 of Programming languages: Concepts & constructs by R. Sethi (2ND EDITION). Addison-Wesley, 1996.

Transcription:

Chapter 7 Control I Expressions and Statements Expressions Conditional Statements and Guards Loops and Variation on WHILE The GOTO Controversy Exception Handling

Values and Effects Important Concepts in Programming Languages Values Effects Expressions Statements Functions Complicating Factors expressions with side effects functions with side effects Procedures subprograms Programming Languages 2

Control Structures Implicit Control Flow the evaluation order of operands in an expression the execution in sequence of statements Explicit Control Flow structured control statements single-entry, single-exit in principle Preemptive Control Mechanism exception handling Programming Languages 3

Expressions Expressions are composed of operators and operands functions and arguments Classifying Operands According to the number of operands required unary - x binary x + y ternary x? y : z According to the positions of the operators infix x + y most languages prefix + x y LISP postfix x y + Postscript, FORTH Programming Languages 4

Evaluation Order of Expressions Applicative Order Evaluation operands are evaluated first and then, the operators are applied to the operands Normal Order Evaluation operators are evaluated before the operands What does it mean to evaluate operators? explained later Programming Languages 5

Applicative Order Example (3+4)*(5-6) 7*(5-6) (3+4)*-1 7*-1-7 In most languages, the evaluation order of operands (or the arguments) is not specified. Programming Languages 6

Evaluation Order and Side-Effects When the expressions may have side-effects, programs may be incorrect due to this fact. Example In the right C program, the function f has a side-effect. Guess the output! Some operators may have side effects Assignment operators in C #include <stdio.h> int x = 1; int f(void) { x += 1; return x; } int p( int a, int b) { return a + b; } main() { printf("%d\n",p(x,f())); return 0; } Programming Languages 7

Evaluation Order Specified Operators Sequence Operators x = (y+1,x+y,x+1) Logical And and Logical Or logical binary operators may be short-circuited If Expressions c? e1 : e2 Case Expressions case e0 of a => e1 b => e2 c => e3 ; Programming Languages 8

Short-Circuit Evaluation The short-circuit evaluation enables compact notations with the short-circuit evaluation if (x!= 0 && y%x == 1)... without the short-circuit evaluation if (x!= 0) if (y%x == 1)... Some languages support the both kinds of Boolean operators In Ada, and, or and then, or else not short-circuited short-circuited Programming Languages 9

Normal Order Evaluation The evaluation of operators? Think of user defined functions. int double(int x){ return x+x; } int square(int x){ return x*x; } square(double(2)) double(2)*double(2) (2+2)*double(2) double(2)*(2+2) 4*double(2) double(2)*4 4*(2+2) (2+2)*4 4*4 16 Programming Languages 10

Conditional Statements In a Conditional Statement, a group of statements is executed only under certain conditions. Kinds of Conditional Statements Single or Binary Selection: if and if-else statement Multiple Selection: case- and switch-statement Programming Languages 11

Guarded If Due to E. W. Dijkstra Nondeterministic selection of statements if B 1 -> S 1 B 2 -> S 2... When one of B i, say B k, is true, then the S k is executed. B n -> S n fi Programming Languages 12

Dangling-Else Problem Which if is the following else matched? if (e1) if (e2) s1 else s2 Solutions of Dangling-Else Problem most closely nested rule The else is to be associated with the closest prior if that does not already have an else part bracketing keyword The if statement should be ended with a special keyword if fi Ada provides elsif for nested if. (Compare the followings) if e1 then S1 else if e2 then S2 else if e3 then S3 end if ; end if ; end if; if e1 then S1 elsif e2 then S2 elsif e3 then S3 end if ; Programming Languages 13

Case- and Switch-Statements A kind of Guarded If where the guards are ordinal values. Switch Statements in C falls through semantics each case value should be computed into a single constant in compile-time Case Statements in Ada case values may be grouped (i.e. case values can be listed using vertical bars and subranges) case values must be exhaustive (more safe) Case Expressions in ML the case construct should return a value (because it is an expression) the cases are patterns (the default case may be represented using the wildcard pattern) Programming Languages 14

Guarded Do Due to E. W. Dijkstra The statement is repeated until all the guards are false. do B 1 -> S 1 B 2 -> S 2... When one of B i, say B k, is true, then the S k is executed. B n -> S n od Programming Languages 15

While Loop A guarded do with only one guard. The do-while loop is a syntactic sugar of while. do S while (e); S; while (e) S; Multiple termination points can be made using the break statement (cf. continue statement) Programming Languages 16

For Loop Implements the counter controlled repetition Good for array processing Note) ISO Standard C The scope of the counter variable (index variable) is generally limited to the inside of the loop Some restrictions may be imposed on the index variable, say i, for the optimization of the loop: i cannot be changed within the loop body. i is undefined after the loop terminates. i must be of restricted type and cannot be declared in other ways. Programming Languages 17

Design Issues of the For Loops Are the loop bounds evaluated only once? Should the loop body be executed when the lower bound is greater than the upper bound? Is it possible to exit the loop early? (exit or break statement) What restrictions should be imposed on the index variable? Programming Languages 18

Iterator Iterator in CLU provides a general form of for-loop constructs similar to a history-sensitive function adopted by some object-oriented languages as iterator objects... for c: char in stringchars(s) do... stringchars = iter (s: string) yields (char); index: int := 1; limit: int := string$size(s); while index <= limit do yield (string$fetch(s, index)) index := index + 1; end; end stringchars; The iterator stringchars yields each character from the argument string. Programming Languages 19

Spaghetti Code due to GOTO Compare the following codes. IF (X.GT.0) GOTO 10 IF (X.LT.0) GOTO 20 X = 1 GOTO 30 10 X = X + 1 GOTO 30 20 X = -X GOTO 10 30 CONTINUE if (x > 0) x = x + 1; else if (x < 0) { x = -x; x = x + 1; } else x = 1; Programming Languages 20

Theoretical Foundation Theoretical Foundation on Structured Control Böhm and Jacopini, 1996 Every possible control structure could be expressed using structured control constructs: sequence structures selection structures repetition structures Programming Languages 21

The GOTO Controversy GO TO Statement Considered Harmful Dijkstra, 1968 GOTO considered harmful considered harmful Rubin, 1987 As a result Significant restrictions are imposed on the use of GOTO. Java replaces GOTO with labeled break and labeled continue. Java makes goto into a reserved word. Programming Languages 22

Exception Handling Properties of Exceptions Implicit Control Structure: There is no syntactic indication for the transfer of control. Preemptive Control Structure: The normal program control is interrupted to handle exceptional cases. Kinds of Exceptions Asynchronous Exceptions occur at any moment hardware failure, communication failure Synchronous Exceptions occur in direct response to actions by the program file-open failure, divide-by-zero Programming Languages 23

Exception Handling Scenario normal control flow unusual event raise or throw exception handler Programming Languages 24

Design Issues of Exception Handling Exceptions What exceptions are predefined? Can they be disabled? Can user-defined exceptions be created? What is the scope of exceptions? Handlers How are handlers defined? What default handlers are provided? Can the predefined handlers be replaced? Control How is the control passed to a handler? Where does the control pass after the handler is executed? What run-time environment remains after the handler executes? Programming Languages 25

Exceptions (Language Examples) Exception Declaration Additional Data of Exceptions Scope Rule ML allowed allowed Ada allowed not allowed the same scope rule as other declarations C++ not allowed but any type can be an exception allowed Programming Languages 26

Handlers (Language Examples) C++ Ada ML Handler Syntax try { } catch (type1 var1){ } catch (type2 var2){ } begin exception when exception1 => when exception2 => val name = handle exception1 => exception2 => Redefining the Default Handlers allowed not allowed but can be disabled not allowed Programming Languages 27

Control Exception Raise system-defined exceptions: automatically raised, may be manually raised user-defined exceptions: manually raised only Exception Propagation If no handlers found, then the handler section of the enclosing block is consulted If no handlers found until the outermost block is reached, then the default handler is called Return from Handler Resumption Model: the control is returned back to the point where the exception was first raised. Termination Model: the control is transferred to the code following the executed handler. (mostly used) Programming Languages 28

Exception Specification Exception Specification a list of exceptions attached to a subprogram the subprogram can raise only those exceptions in the exception specification Advantages of Exception Specification the compiler can perform some optimization using this information the compiler can identify the needless handlers Exception Handling Example See Fig. 7.11 (Recursive Descent Calculator in C++) Programming Languages 29