CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 12.

Slides:



Advertisements
Similar presentations
Semantic Analysis Chapter 6. Two Flavors  Static (done during compile time) –C –Ada  Dynamic (done during run time) –LISP –Smalltalk  Optimization.
Advertisements

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.
Expressions and Statements. 2 Contents Side effects: expressions and statements Expression notations Expression evaluation orders Conditional statements.
Names and Bindings.
COP4020 Programming Languages Expression and assignment Prof. Xin Yuan.
ISBN Chapter 7 Expressions and Assignment Statements.
Programming Languages Marjan Sirjani 2 2. Language Design Issues Design to Run efficiently : early languages Easy to write correctly : new languages.
Lecture 16 Subroutine Calls and Parameter Passing Semantics Dragon: Sec. 7.5 Fischer: Sec Procedure declaration procedure p( a, b : integer, f :
Gary MarsdenSlide 1University of Cape Town Statements & Expressions Gary Marsden Semester 2 – 2000.
CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 18.
Chapter 8 Runtime Support. How program structures are implemented in a computer memory? The evolution of programming language design has led to the creation.
Chapter 7 Expressions and Assignment Statements. Copyright © 2012 Addison-Wesley. All rights reserved.1-2 Chapter 7 Topics Introduction Arithmetic Expressions.
ALGOL 60 Design by committee of computer scientists: Naur, Backus, Bauer, McCarthy, van Wijngaarden, Landin, etc. Design by committee of computer scientists:
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Control Structures. Hierarchical Statement Structure Standard in imperative languages since Algol60. Exceptions: Early FORTRAN, COBOL, early BASIC, APL.
Chapter 7 Expressions and Assignment Statements. Copyright © 2007 Addison-Wesley. All rights reserved. 1–2 Arithmetic Expressions Arithmetic evaluation.
ISBN Chapter 7 Expressions and Assignment Statements.
JavaScript, Third Edition
Chapter 7: Runtime Environment –Run time memory organization. We need to use memory to store: –code –static data (global variables) –dynamic data objects.
7-1 Chapter 7: Expressions and Assignment Statements Arithmetic Expressions –the fundamental means of specifying computations in a programming language.
Chapter 7 Expressions and Assignment Statements. Chapter 7 Topics 1-2 Introduction Arithmetic Expressions Overloaded Operators Type Conversions Relational.
Ryan Chu. Arithmetic Expressions Arithmetic expressions consist of operators, operands, parentheses, and function calls. The purpose is to specify an.
C H A P T E R S E V E N Expressions and Assignment Statements.
Names Variables Type Checking Strong Typing Type Compatibility 1.
5-1 Chapter 5: Names, Bindings, Type Checking, and Scopes Variables The Concept of Binding Type Checking Strong Typing Type Compatibility Scope and Lifetime.
CS 2104 Prog. Lang. Concepts Subprograms
Runtime Environments Compiler Construction Chapter 7.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
PLLab, NTHU,Cs2403 Programming Languages Expression and control structure Kun-Yuan Hsieh Programming Language Lab., NTHU.
1 Control Flow: Expressions, Sequencing & Selection (Section ) A compilation of material developed by Felix Hernandez-Campos and Michael Scott.
Introduction A variable can be characterized by a collection of properties, or attributes, the most important of which is type, a fundamental concept in.
Basic Semantics Associating meaning with language entities.
CSI 3120, Expressions and assignment, page 1 Expressions and assignment Points for discussion Arithmetic expressions Overloading Logical expressions Assignment.
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.
CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 9.
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
Chapter 7 Expressions and Assignment Statements. Copyright © 2009 Addison-Wesley. All rights reserved.1-2 Chapter 7 Topics Introduction Arithmetic Expressions.
Types(1). Lecture 52 Type(1)  A type is a collection of values and operations on those values. Integer type  values..., -2, -1, 0, 1, 2,...  operations.
ISBN Chapter 7 Expressions and Assignment Statements.
Slide 1 WEEK 8 Imperative Programming Original by Vitaly Shmatikov.
How to execute Program structure Variables name, keywords, binding, scope, lifetime Data types – type system – primitives, strings, arrays, hashes – pointers/references.
Chapter Seven: Expressions and Assignment Statements Lesson 07.
LECTURE 18 Control Flow. CONTROL FLOW Sequencing: the execution of statements and evaluation of expressions is usually in the order in which they appear.
Names, Scope, and Bindings Programming Languages and Paradigms.
Copyright © 2009 Elsevier Chapter 6:: Control Flow Programming Language Pragmatics Michael L. Scott.
Chapter 1: Preliminaries Lecture # 2. Chapter 1: Preliminaries Reasons for Studying Concepts of Programming Languages Programming Domains Language Evaluation.
1 Compiler Construction Run-time Environments,. 2 Run-Time Environments (Chapter 7) Continued: Access to No-local Names.
C Program Control September 15, OBJECTIVES The essentials of counter-controlled repetition. To use the for and do...while repetition statements.
Expressions and Assignment Statements
Information and Computer Sciences University of Hawaii, Manoa
Expressions and Assignment Statements
Lecture 18 Control Flow.
Chapter 7: Expressions and Assignment Statements
CS 326 Programming Languages, Concepts and Implementation
Expressions and Assignment Statements
Expressions and Assignment
CS 326 Programming Languages, Concepts and Implementation
Chapter 7: Expressions and Assignment Statements
Expressions and Assignment Statements
Chap. 6 :: Control Flow Michael L. Scott.
Control Flow Chapter 6.
Expressions and Assignment Statements
Chap. 6 :: Control Flow Michael L. Scott.
Languages and Compilers (SProg og Oversættere)
CSE 3302 Programming Languages
Expressions and Assignment Statements
Presentation transcript:

CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 12

22/69 Sequencing Why is it good to have no side-effects? Ensure that functions are idempotent: −Can call a function repeatedly with same parameters → same result −The moment when a function is called does not affect the surrounding code Are these equivalent? a = f(b);c = d; c = d;a = f(b); No, if f changes d Easier to check the program correctness Easier code improvement – safe rearrangement of expressions

33/69 Sequencing In imperative languages: List of statements – introduced by begin...end or {...} delimiters Such a list: −is called a compound statement (block) −defines a local scope for variables declared in the block −may have a return value – last statement in list Still desire for lack of side-effects: −Euclid and Turing – functions are not allowed side-effects, only procedures can −Ada – functions can change global variables, but not their own parameters

44/69 Expressions and Statements Expressions – generate a value Statements – just have side effects (through assignments) Statement-oriented languages −Distinguish between statements and expressions −Statements are the building blocks of programs −Variables are assigned values generated by expressions −What a statement returns is not important (not defined) −Examples: most imperative languages Expression-oriented languages −No distinction, everything is an expression and must return a value −Examples: Algol 68, functional languages (Lisp, Scheme, ML) C is somewhere in between

55/69 Expressions and Statements Example in Algol-68: begin a := if b < c then d else e; x := begin f(y); g(z) end; g(d); p := q := r; 2 + 3; end Value of the if...then...else expression – the then part or the else part, depending on the condition −a is assigned d or e Value of the begin...end expression – the last expression in sequence −x is assigned g(z) −the value returned by f(y) is ignored −the value returned by g(d) is ignored −the outer begin...end expression returns 5 Value of the assignment – the value that is assigned −the assignment q := r returns r, which is assigned to p

66/69 Expression Evaluation Expression −either a simple object (constant or variable) or an operator applied on a collection of operands, each of which being an expression −it results in a value Operators can be +, -, *, /, etc or function names Operands can be simple objects (constants or variables), or expressions Expressions in "pure" form (in "pure" functional languages) have no side effects - referential transparency Notation −prefix −infix −postfix

77/69 RPS

88/69 Expression Evaluation Algol-family languages (Pascal, C) – distinguish between function calls and built-in operators my_func (a, b)- prefix notation for function calls a + b- infix notation for binary operators -c- prefix notation for unary operators a := if b <> 0 then c else d- in Algol, if...then...else is a three- operand infix operator Lisp-family languages –no distinctions, Cambridge Polish notation everywhere (prefix, with parentheses around expression) (my_func a b) (+ a b) (- c) Postscript, Forth – use mostly postfix notation C++ – define operators as shorthand notations for function calls a + b  a.operator+(b)

99/69 Precedence and Associativity How is the following expression evaluated? 9-3*2+1 Precedence - rules to specify that some operators group "more tightly" than others, in the absence of parentheses (* and / have higher precedence that + and -) Associativity - rules to specify whether sequences of operators of equal precedence group to the right or left (arithmetic operators have left associativity) These issues arise only for infix notation, not for prefix or postfix

1010/69 Precedence and Associativity Precedence: −C – 15 levels of precedence - too many to remember −Does + have higher precedence than >> ? −Pascal – 3 levels of precedence - too few for good semantics −Precedence is not specified for some operators if A < B and C < D then(* ouch *) −This condition evaluates to ((A < B) and C) < D −APL – all operators have equal precedence, parentheses must be used Associativity: −In general, associativity is towards left. When is it towards right? −In assignments: a = b = c + d

1111/69 Assignments What is a variable? −It actually depends on the context in which it appears In C, what is the meaning of a in the following: d = a; a = b + c; Expressions that denote locations → l-values Expressions that denote values → r-values a 5+1 NULL b[i] p->s f(a) // the value of a // the location (address) of a has both r-value and l-value only r-value only r-value (it is a constant) both has r-value, unless it doesn't return anything (void) may have l-value, if it returns an address (pointer)

1212/69 Assignments Consider the code: b := 2; c := b; a := b + c; Value model (left) −Variable – a named container for a value −Examples: C, Pascal, Ada Reference model (right) −Variable - a named reference (pointer) to a value −Examples: Lisp, Scheme, ML (functional languages), Clu, Smalltalk −Important to distinguish between: −variables that refer to the same object −variables that refer to different objects, with same values Implementation: (eq?) (equal?) OR

1313/69 Assignment vs. Initialization What is the difference between: int a = 1;ANDint a; a = 1; −In the first case, if a is statically allocated, the value 1 is placed into location a at compile time −In the second case, the assignment will incur execution cost at run- time What is the difference between: void f (int x)AND { int a = 1; } void f (int x) { int a; a = 1; } −No difference, the value 1 is placed into a at runtime anyway, as the memory location for a is determined at run-time (on the stack)

1414/69 Assignment vs. Initialization Why is initialization also useful? −To prevent using variables before they are assigned a value -> initialize them when are first declared Can initialization be done automatically (with some default value) when the programmer doesn't do it? −Statically allocated variables – in C they are guaranteed to be filled with zero bits, if not otherwise initialized −Dynamically allocated variables (on stack or heap) – expensive to initialize automatically, because it cannot be done at compile time

1515/69 Assignment vs. Initialization Can the use of uninitialized variables be detected at run- time (dynamic semantic error)? Uninitialized floating-point variables −can be filled with a NaN ("not a number") value −any use of NaN in computation → signal error For other types, where all possible values are legitimate −need to use extra space for a flag −too expensive

1616/69 Assignment vs. Initialization Particular interest in C++ class T { char * s; int N;// number of elements... }; For an object containing (as a data member) a variable length array: −assignment −initialization −the assignment operator must generally deallocate the old space and allocate new space −the constructor must simply allocate space

1717/69 Combination Assignment Operators Update a variable: a = a + 1; b.c[3].d = b.c[3].d * e; Why is this not desirable? −Hard to write and to read −Redundant address calculations −Address calculation may have side effects: a[f(x)] = a[f(x)] + 3; If f has side effects (don't want them twice), need to rewrite as: j = f(x); a[j] = a[j] + 3;

1818/69 Combination Assignment Operators To update a variable - use combination assignment operators (in C): a += 1; b.c[3].d *= e; C also provides prefix and postfix increment and decrement operations: int i = 5; A[++i] = b; int k = 5; A[k--] = b; Pointer arithmetic in C: int * p;... p += 3; // actually changes p to point 3*sizeof(int) bytes higher in memory // A[5] is assigned value b, k becomes 4 // i becomes 6, A[6] is assigned value b

1919/69 Ordering within Expressions Precedence and associativity −Define the order in which operators are applied −Do not specify the order of evaluating operands a - f(b) - c*d// is f(b) or c*d evaluated first? g (a, f(b), c*d)// is f(b) or c*d evaluated first? Why is evaluation order important? −Side effects – f may modify the values of c or d −Code improvement: a*b + f(c)// a*b would need a register to save the result // better to evaluate f(c) first, so that f has all registers available

2020/69 Ordering within Expressions Can generate problems – computer arithmetic: −If b, c, d are all positive and close to the maximum value that can be represented: b - c + d// OK b + d - c// arithmetic overflow Importance of code improvement → most languages impose no order of evaluation −the compiler can choose whatever ordering produces faster code −exception: Java - always left-to-right evaluation Rearranging order of expressions (in Fortran): a = b + c d = c + e + b a = b + c d = a + e Produce code equivalent to:

2121/69 Short-Circuit Evaluation Short-circuit evaluation −used in the evaluation of Boolean expressions −evaluate only as much as needed to compute the value of an expression Examples: if (b != 0 && a/b == c)... if (p && p->foo)... if (i >= 0 && i x)... C – short-circuit evaluation Pascal – only regular evaluation of Boolean expressions Clu – both: and and or- regular evaluation cand and cor- short-circuit evaluation

2222/69 Structured and Unstructured Flow Control flow in assembly language - conditional and unconditional jumps Late 1960s, 1970s - debate on merits and evils of goto −Dijkstra article: "GOTO Statement Considered Harmful" −Rubin article: "'GOTO Considered Harmful' Considered Harmful" Ada – allows goto in limited contexts Fortran 90, C++ – allows goto just for compatibility Java – does not allow it, but keeps goto as a keyword Early imperative languages (Fortran, Cobol, PL/I) - mimic this approach: if A.lt. B goto :...

2323/69 Structured and Unstructured Flow Abandonment of goto → apparition of structured programming −instead of labels and jumps - lexically nested blocks −selection through if...then...else −iteration through for, while Remaining cases when goto would be useful: Mid-loop exit while true do begin readln (line); if all_blanks (line) then goto 100; consume_line (line) end; 100:... C provides break to do this

2424/69 Structured and Unstructured Flow Mid-loop continue while not eof do begin readln (line); if all_blanks (line) then goto 100; consume_line (line) 100: end; C provides continue to do this

2525/69 Structured and Unstructured Flow Early return from subroutines procedure consume_line (var line: string);... begin... (*if the rest of line is a comment, ignore it *) if line[i] = '%' then goto 100; : end; C provides return to do this

2626/69 Structured and Unstructured Flow Backing out of deeply nested blocks −recovery from errors −such conditions are called exceptions If implemented with goto out of subroutines Some languages (Clu, Ada, C++, Java, Common Lisp) provide an exception handling mechanism to do this −in C++: use throw and catch −need to "repair" the stack of each current subroutine invocation

2727/69 Selection Use the if...then...else notation introduced in Algol 60: if condition then statement else if condition then statement... else if condition then statement In Algol 60 and Pascal – only one statement is allowed (or a compound statement using begin...end)

2828/69 Selection Ambiguity – with what if does else associate? if a = b then if c = d then statement1 else statement2 −Pascal – "disambiguating rule“: else associates with the last unmatched if

2929/69 Selection Scheme – ambiguity solved by parentheses (if (= a b) x y); only one expression allowed in each arm (cond ((= a b) p q ; several expressions allowed in each arm r) ; the value of last one is returned ((= a c) s t) (else u v))

3030/69 Announcements Readings −Rest of Chapter 6 Homework −HW 4 out – due on October 13 −Submission −at the beginning of class −with a title page: Name, Class, Assignment #, Date −everything stapled together −preferably typed