# Control Flow. Stephen A. Edwards. Fall Columbia University

Save this PDF as:

Size: px
Start display at page:

## Transcription

1 Control Flow Stephen A. Edwards Columbia University Fall 2013

2 Control Flow Time is Nature s way of preventing everything from happening at once. Scott identifies seven manifestations of this: 1. Sequencing foo(); bar(); 2. Selection if (a) foo(); 3. Iteration while (i<10) foo(i); 4. Procedures foo(10,20); 5. Recursion foo(int i) { foo(i-1); 6. Concurrency foo() bar() 7. Nondeterminism do a -> foo(); [] b -> bar();

3 Ordering Within Expressions What code does a compiler generate for a = b + c + d; Most likely something like tmp = b + c; a = tmp + d; (Assumes left-to-right evaluation of expressions.)

4 Order of Evaluation Why would you care? Expression evaluation can have side-effects. Floating-point numbers don t behave like numbers.

5 Side-effects int x = 0; int foo() { x += 5; return x; int bar() { int a = foo() + x + foo(); return a; What does bar() return?

6 Side-effects int x = 0; int foo() { x += 5; return x; int bar() { int a = foo() + x + foo(); return a; What does bar() return? GCC returned 25. Sun s C compiler returned 20. C says expression evaluation order is implementation-dependent.

7 Side-effects Java prescribes left-to-right evaluation. class Foo { static int x; static int foo() { x += 5; return x; public static void main(string args[]) { int a = foo() + x + foo(); System.out.println(a); Always prints 20.

8 Number Behavior Basic number axioms: a + x = a if and only if x = 0 Additive identity (a + b) + c = a + (b + c) Associative a(b + c) = ab + ac Distributive

9 Misbehaving Floating-Point Numbers 1e20 + 1e-20 = 1e20 1e-20 1e20 (1 + 9e-7) + 9e (9e-7 + 9e-7) 9e-7 1, so it is discarded, however, 1.8e-6 is large enough ( ) = requires too much intermediate precision.

10 What s Going On? Floating-point numbers are represented using an exponent/significand format: {{ {{ 8-bit exponent 23-bit significand = = = 5.5. What to remember: {{ {{ represented rounded

11 What s Going On? Results are often rounded: {{ rounded When b c, b + c is small, so ab + ac a(b + c) because precision is lost when ab is calculated. Moral: Be aware of floating-point number properties when writing complex expressions.

12 Short-Circuit Evaluation When you write if (disaster_could_happen) avoid_it(); else cause_a_disaster(); cause_a_disaster() is not called when disaster_could_happen is true. The if statement evaluates its bodies lazily: only when necessary. The section operator? : does this, too. cost = disaster_possible? avoid_it() : cause_it();

13 Logical Operators In Java and C, Boolean logical operators short-circuit to provide this facility: if (disaster_possible case_it()) {... cause_it() only called if disaster_possible is false. The && operator does the same thing. Useful when a later test could cause an error: int a[10]; if (i => 0 && i < 10 && a[i] == 0) {...

14 Unstructured Control-Flow Assembly languages usually provide three types of instructions: Pass control to next instruction: add, sub, mov, cmp Pass control to another instruction: jmp rts Conditionally pass control next or elsewhere: beq bne blt

15 Unstructured Control-Flow B: BEQ A JMP C A: C: D: BEQ D BEQ B BNE B RTS

16 Structured Control-Flow The object-oriented languages of the 1960s and 70s. Structured programming replaces the evil goto with structured (nested) constructs such as for while break return continue do.. while if.. then.. else

17 Gotos vs. Structured Programming A typical use of a goto is building a loop. In BASIC: 10 PRINT I 20 I = I IF I < 10 GOTO 10 A cleaner version in C using structured control flow: do { printf("%d\n", i); i = i + 1; while ( i < 10 ) An even better version for (i = 0 ; i < 10 ; i++) printf("%d\n", i);

18 Gotos vs. Structured Programming Break and continue leave loops prematurely: for ( i = 0 ; i < 10 ; i++ ) { if ( i == 5 ) continue; if ( i == 8 ) break; printf("%d\n", i); i = 0; Again: if (!(i < 10)) goto Break; if ( i == 5 ) goto Continue; if ( i == 8 ) goto Break; printf("%d\n", i); Continue: i++; goto Again; Break:

19 Escaping from Loops Java allows you to escape from labeled loops: a: for (int i = 0 ; i < 10 ; i++) for ( int j = 0 ; j < 10 ; j++) { System.out.println(i + "," + j); if (i == 2 && j == 8) continue a; if (i == 8 && j == 4) break a;

20 Gotos vs. Structured Programming Pascal has no return statement for escaping from functions/procedures early, so goto was necessary: procedure consume_line(var line : string); begin if line[i] = % then goto 100; (*... *) 100: end In C and many others, return does this for you: void consume_line(char *line) { if (line[0] == % ) return;

21 Loops A modern processor can execute something like 1 billion instructions/second. How many instructions are there in a typical program? Perhaps a million. Why do programs take more than 1ms to run? Answer: loops This insight is critical for optimization: only bother optimizing the loops since everything else is of vanishing importance.

22 Enumeration-Controlled Loops in FORTRAN do 10 i = 1, 10, : continue Executes body of the loop with i=1, 3, 5,..., 9 Tricky things: What happens if the body changes the value of i? What happens if gotos jump into or out of the loop? What is the value of i upon exit? What happens if the upper bound is less than the lower one?

23 Changing Loop Indices Most languages prohibit changing the index within a loop. (Algol 68, Pascal, Ada, FORTRAN 77 and 90, Modula-3) But C, C++, and Java allow it. Why would a language bother to restrict this?

24 Empty Bounds In FORTRAN, the body of this loop is executed once: do 10 i = 10, 1, : continue for i = 10 to 1 by 1 Test is done after the body. Modern languages place the test before the loop. Does the right thing when the bounds are empty. Slightly less efficient (one extra test).

25 Scope of Loop Index What happens to the loop index when the loop terminates? Index is undefined: FORTRAN IV, Pascal. Index is its last value: FORTRAN 77, Algol 60 Index is just a variable: C, C++, Java Tricky when iterating over subranges. What s next? var c : a.. z ; for c := a to z do begin... end; (* what s c? *)

26 Scope of Loop Index Originally in C++, a locally-defined index variable s scope extended beyond the loop: for (int i = 0 ; i < 10 ; i++) {... a = a + i; // Was OK: i = 10 here But this is awkward: for (int i = 0 ; i < 10 ; i++) { for (int i = 0 ; i < 10 ; i++) // Error: i redeclared

27 Scope of Loop Index C++ and Java now restrict the scope to the loop body: for (int i = 0 ; i < 10 ; i++ ) { int a = i; // OK... int b = i; // Error: i undefined... for (int i = 0 ; i < 10 ; i++ ) { // OK Rather annoying: broke many old C++ programs. Better for new code.

28 Algol s Combination Loop for for id := for-list do stmt for-list enumerator (, enumerator )* enumerator expr expr step expr until expr expr while condition Equivalent: for i := 1, 3, 5, 7, 9 do... for i := 1 step 2 until 10 do... for i := 1, i+2 while i < 10 do... Language implicitly steps through enumerators (implicit variable).

29 Mid-test Loops while true do begin readln(line); if all_blanks(line) then goto 100; consume_line(line); end; 100: In Modula-2: LOOP line := ReadLine; WHEN AllBlanks(line) EXIT; ConsumeLine(line) END;

30 Multi-way Branching switch (s) { case 1: one(); break; case 2: two(); break; case 3: three(); break; case 4: four(); break; switch (s) { case 1: goto One; case 2: goto Two; case 3: goto Three; case 4: goto Four; goto Break; One: one(); goto Break; Two: two(); goto Break; Three: three(); goto Break; Four: four(); goto Break; Break: Switch sends control to one of the case labels. Break terminates the statement. Really just a multi-way goto:

31 Implementing multi-way branches switch (s) { case 1: one(); break; case 2: two(); break; case 3: three(); break; case 4: four(); break; Obvious way: if (s == 1) { one(); else if (s == 2) { two(); else if (s == 3) { three(); else if (s == 4) { four(); Reasonable, but we can sometimes do better.

32 Implementing multi-way branches If the cases are dense, a branch table is more efficient: switch (s) { case 1: one(); break; case 2: two(); break; case 3: three(); break; case 4: four(); break; A branch table written using a GCC extension: /* Array of addresses of labels */ static void *l[] = { &&L1, &&L2, &&L3, &&L4 ; if (s >= 1 && s <= 4) goto *l[s-1]; goto Break; L1: one(); goto Break; L2: two(); goto Break; L3: three(); goto Break; L4: four(); goto Break; Break:

33 Recursion and Iteration To compute 10 i=0 f (i ) in C, the most obvious technique is iteration: double total = 0; for ( i = 0 ; i <= 10 ; i++ ) total += f(i);

34 Recursion and Iteration To compute 10 i=0 f (i ) in C, the most obvious technique is iteration: double total = 0; for ( i = 0 ; i <= 10 ; i++ ) total += f(i); But this can also be defined recursively double sum(int i, double acc) { if (i <= 10) return sum(i+1, acc + f(i)); else return acc; sum(0, 0.0);

35 Tail-Recursion and Iteration 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); Notice: no computation follows any recursive calls. Stack is not necessary: all variables dead after the call. Local variable space can be reused. Trivial since the collection of variables is the same. Works in O Caml, too let rec gcd a b = if a = b then a else if a > b then gcd (a - b) b else gcd a (b - a)

36 Tail-Recursion and Iteration 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); Can be rewritten into: int gcd(int a, int b) { start: if ( a==b ) return a; else if ( a > b ) a = a-b; goto start; else b = b-a; goto start; Good compilers, especially those for functional languages, identify and optimize tail recursive functions. Less common for imperative languages, but gcc -O was able to handle this example.

37 Applicative- and Normal-Order Evaluation int p(int i) { printf("%d ", i); return i; void q(int a, int b, int c) { int total = a; printf("%d ", b); total += c; q( p(1), 2, p(3) ); What does this print?

38 Applicative- and Normal-Order Evaluation int p(int i) { printf("%d ", i); return i; void q(int a, int b, int c) { int total = a; printf("%d ", b); total += c; q( p(1), 2, p(3) ); What does this print? Applicative: arguments evaluated before function is called. Result: Normal: arguments evaluated when used. Result: 1 2 3

39 Applicative- vs. and Normal-Order Most languages use applicative order. Macro-like languages often use normal order. #define p(x) (printf("%d ",x), x) #define q(a,b,c) total = (a), \ printf("%d ", (b)), \ total += (c) q( p(1), 2, p(3) ); Prints Some functional languages also use normal order evaluation to avoid doing work. Lazy Evaluation

40 Argument Order Evaluation C does not define argument evaluation order: int p(int i) { printf("%d ", i); return i; int q(int a, int b, int c) { q( p(1), p(2), p(3) ); Might print 1 2 3, 3 2 1, or something else. This is an example of nondeterminism.

41 Nondeterminism Nondeterminism is not the same as random: Compiler usually chooses an order when generating code. Optimization, exact expressions, or run-time values may affect behavior. Bottom line: don t know what code will do, but often know set of possibilities. int p(int i) { printf("%d ", i); return i; int q(int a, int b, int c) { q( p(1), p(2), p(3) ); Will not print It will print one of 1 2 3, 1 3 2, 2 1 3, 2 3 1, 3 1 2, 3 2 1

42 Nondeterminism Nondeterminism lurks in most languages in one form or another. Especially prevelant in concurrent languages. Sometimes it s convenient, though: if a >= b -> max := a [] b >= a -> max := b fi Nondeterministic (irrelevant) choice when a=b. Often want to avoid it, however.

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

Control Structures In Text: Chapter 8 1 Control structures Selection One-way Two-way Multi-way Iteration Counter-controlled Logically-controlled Gotos Guarded statements Outline Chapter 8: 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)

Maria Hybinette, UGA Big Picture: Control Flow Ordering in Program Execution CSCI: 4500/6500 Programming Languages Control Flow Chapter 6 1 Ordering/Flow Mechanisms:! Sequencing (statements executed (evaluated)

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

Programming Languages Third Edition Chapter 9 Control I Expressions and Statements Objectives Understand expressions Understand conditional statements and guards Understand loops and variation on WHILE

### Design Issues. Subroutines and Control Abstraction. Subroutines and Control Abstraction. CSC 4101: Programming Languages 1. Textbook, Chapter 8

Subroutines and Control Abstraction Textbook, Chapter 8 1 Subroutines and Control Abstraction Mechanisms for process abstraction Single entry (except FORTRAN, PL/I) Caller is suspended Control returns

### Control Flow. CSE 307 Principles of Programming Languages Stony Brook University

Control Flow CSE 307 Principles of Programming Languages Stony Brook University http://www.cs.stonybrook.edu/~cse307 1 Specifying the Semantics of Programs Operational Semantics: Give how a program would

### CMPT 379 Compilers. Anoop Sarkar. 11/13/07 1. TAC: Intermediate Representation. Language + Machine Independent TAC

CMPT 379 Compilers Anoop Sarkar http://www.cs.sfu.ca/~anoop 11/13/07 1 TAC: Intermediate Representation Language Specific Language + Machine Independent Machine Dependent Front End AST Intermediate Code

### Chapter 8. Statement-Level Control Structures

Chapter 8 Statement-Level Control Structures Chapter 8 Topics Introduction Selection Statements Iterative Statements Unconditional Branching Guarded Commands Conclusions 1-2 Levels of Control Flow Within

### Expressions vs statements

Expressions vs statements Every expression results in a value (+side-effects?): 1+2, str.length(), f(x)+1 Imperative prg: Statements have just side-effects, no value: (for, if, break) Assignment is statement/expression

### C Language Part 2 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

C Language Part 2 (Minor modifications by the instructor) 1 Scope Rules A variable declared inside a function is a local variable Each local variable in a function comes into existence when the function

### Object Code (Machine Code) Dr. D. M. Akbar Hussain Department of Software Engineering & Media Technology. Three Address Code

Code Generation Intermediate Code? Assembly Code Object Code (Machine Code) 1 Intermediate Code P-Code Three Address Code 2 Compiler Construction F6S 1 Intermediate Representation Abstract Syntax Tree

### Procedures and Stacks

Procedures and Stacks Daniel Sanchez Computer Science & Artificial Intelligence Lab M.I.T. March 15, 2018 L10-1 Announcements Schedule has shifted due to snow day Quiz 2 is now on Thu 4/12 (one week later)

### Imperative Programming Languages (IPL)

Imperative Programming Languages (IPL) Definitions: The imperative (or procedural) paradigm is the closest to the structure of actual computers. It is a model that is based on moving bits around and changing

### An Introduction to Scheme

An Introduction to Scheme Stéphane Ducasse stephane.ducasse@inria.fr http://stephane.ducasse.free.fr/ Stéphane Ducasse 1 Scheme Minimal Statically scoped Functional Imperative Stack manipulation Specification

### CSC 2400: Computing Systems. X86 Assembly: Function Calls"

CSC 24: Computing Systems X86 Assembly: Function Calls" 1 Lecture Goals! Challenges of supporting functions" Providing information for the called function" Function arguments and local variables" Allowing

### Chapter 11 Introduction to Programming in C

C: A High-Level Language Chapter 11 Introduction to Programming in C Original slides from Gregory Byrd, North Carolina State University Modified slides by Chris Wilcox, Colorado State University Gives

### Chapter 8. Statement-Level Control Structures ISBN

Chapter 8 Statement-Level Control Structures ISBN 0-321-49362-1 Chapter 8 Topics Introduction Selection Statements Iterative Statements Unconditional Branching Guarded Commands Conclusions Copyright 2012

### 4. Functions. March 10, 2010

March 10, 2010 Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 1 of 40 Outline Recapitulation Functions Part 1 What is a Procedure? Call-by-value and Call-by-reference Functions

### Intermediate Representa.on

IR Intermediate Representa.on CMPT 379: Compilers Instructor: Anoop Sarkar anoopsarkar.github.io/compilers-class Intermediate Representation Language Specific Language + Machine Independent Machine Dependent

### Introduction to Object-Oriented Programming

Introduction to Object-Oriented Programming Conditional Execution Christopher Simpkins chris.simpkins@gatech.edu CS 1331 (Georgia Tech) Conditional Execution 1 / 14 Structured Programming In reasoning

### Abstract Syntax Trees

Abstract Syntax Trees COMS W4115 Prof. Stephen A. Edwards Fall 2007 Columbia University Department of Computer Science Parsing and Syntax Trees Parsing decides if the program is part of the language. Not

### Machine Language Instructions Introduction. Instructions Words of a language understood by machine. Instruction set Vocabulary of the machine

Machine Language Instructions Introduction Instructions Words of a language understood by machine Instruction set Vocabulary of the machine Current goal: to relate a high level language to instruction

### Intel x86 Jump Instructions. Part 5. JMP address. Operations: Program Flow Control. Operations: Program Flow Control.

Part 5 Intel x86 Jump Instructions Control Logic Fly over code Operations: Program Flow Control Operations: Program Flow Control Unlike high-level languages, processors don't have fancy expressions or

### Language Design COMS W4115. Prof. Stephen A. Edwards Fall 2006 Columbia University Department of Computer Science

Language Design COMS W4115 Katsushika Hokusai, In the Hollow of a Wave off the Coast at Kanagawa, 1827 Prof. Stephen A. Edwards Fall 2006 Columbia University Department of Computer Science Language Design

### Topics Covered Thus Far CMSC 330: Organization of Programming Languages

Topics Covered Thus Far CMSC 330: Organization of Programming Languages Names & Binding, Type Systems Programming languages Ruby Ocaml Lambda calculus Syntax specification Regular expressions Context free

### Parameters. Chapter Eighteen Modern Programming Languages, 2nd ed. 1

Parameters Chapter Eighteen Modern Programming Languages, 2nd ed. 1 Parameter Passing int plus(int a, int b) { return a+b; int x = plus(1,2); method body formal parameters actual parameters method call

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

Control Statements Control Statements All programs could be written in terms of only one of three control structures: Sequence Structure Selection Structure Repetition Structure Sequence structure The

### Assembly Language: Function Calls

Assembly Language: Function Calls 1 Goals of this Lecture Help you learn: Function call problems x86-64 solutions Pertinent instructions and conventions 2 Function Call Problems (1) Calling and returning

### Functions. x y z. f (x, y, z) Take in input arguments (zero or more) Perform some computation - May have side-effects (such as drawing)

2.1 Functions Functions Take in input arguments (zero or more) Perform some computation - May have side-effects (such as drawing) Return one output value Input Arguments x y z f Return Value f (x, y, z)

### CS 314 Principles of Programming Languages. Lecture 9

CS 314 Principles of Programming Languages Lecture 9 Zheng Zhang Department of Computer Science Rutgers University Wednesday 5 th October, 2016 Zheng Zhang 1 CS@Rutgers University Class Information Homework

### Chapter 5 Names, Binding, Type Checking and Scopes

Chapter 5 Names, Binding, Type Checking and Scopes Names - We discuss all user-defined names here - Design issues for names: -Maximum length? - Are connector characters allowed? - Are names case sensitive?

### Lecture 5: Methods CS2301

Lecture 5: Methods NADA ALZAHRANI CS2301 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. 2 Solution public static int sum(int i1, int i2) { int

### Chapter 7:: Data Types. Mid-Term Test. Mid-Term Test (cont.) Administrative Notes

Chapter 7:: Data Types Programming Language Pragmatics Michael L. Scott Administrative Notes Mid-Term Test Thursday, July 27 2006 at 11:30am No lecture before or after the mid-term test You are responsible

### CSE 3302 Programming Languages Lecture 5: Control

CSE 3302 Programming Languages Lecture 5: Control (based on the slides by Chengkai Li) Leonidas Fegaras University of Texas at Arlington CSE 3302 L5 Fall 2009 1 Control Control: what gets executed, when,

### Begin at the beginning

Begin at the beginning Expressions (Syntax) Exec-time Dynamic Values (Semantics) Compile-time Static Types 1. Programmer enters expression 2. ML checks if expression is well-typed Using a precise set of

### CSE 504. Expression evaluation. Expression Evaluation, Runtime Environments. One possible semantics: Problem:

Expression evaluation CSE 504 Order of evaluation For the abstract syntax tree + + 5 Expression Evaluation, Runtime Environments + + x 3 2 4 the equivalent expression is (x + 3) + (2 + 4) + 5 1 2 (. Contd

### Introduction Primitive Data Types Character String Types User-Defined Ordinal Types Array Types. Record Types. Pointer and Reference Types

Chapter 6 Topics WEEK E FOUR Data Types Introduction Primitive Data Types Character String Types User-Defined Ordinal Types Array Types Associative Arrays Record Types Union Types Pointer and Reference

### Organization of Programming Languages (CSE452) Why are there so many programming languages? What makes a language successful?

Organization of Programming Languages (CSE452) Instructor: Dr. B. Cheng Fall 2004 1 Why are there so many programming languages? Evolution -- we've learned better ways of doing things over time Socio-economic

### 22c:111 Programming Language Concepts. Fall Types I

22c:111 Programming Language Concepts Fall 2008 Types I Copyright 2007-08, The McGraw-Hill Company and Cesare Tinelli. These notes were originally developed by Allen Tucker, Robert Noonan and modified

### Chapter 3:: Names, Scopes, and Bindings (cont.)

Chapter 3:: Names, Scopes, and Bindings (cont.) Programming Language Pragmatics Michael L. Scott Review What is a regular expression? What is a context-free grammar? What is BNF? What is a derivation?

### Memory Management and Run-Time Systems

TDDD55 Compilers and Interpreters TDDB44 Compiler Construction Memory Management and Run-Time Systems Part of the Attribute Grammar Material Presented at the Beginning of this Lecture Peter Fritzson IDA,

### A Deterministic Concurrent Language for Embedded Systems

A Deterministic Concurrent Language for Embedded Systems Stephen A. Edwards Columbia University Joint work with Olivier Tardieu SHIM:A Deterministic Concurrent Language for Embedded Systems p. 1/30 Definition

### Introduction to Programming (Java) 4/12

Introduction to Programming (Java) 4/12 Michal Krátký Department of Computer Science Technical University of Ostrava Introduction to Programming (Java) 2008/2009 c 2006 2008 Michal Krátký Introduction

### Time : 1 Hour Max Marks : 30

Total No. of Questions : 6 P4890 B.E/ Insem.- 74 B.E ( Computer Engg) PRINCIPLES OF MODERN COMPILER DESIGN (2012 Pattern) (Semester I) Time : 1 Hour Max Marks : 30 Q.1 a) Explain need of symbol table with

### CSC 2400: Computing Systems. X86 Assembly: Function Calls

CSC 24: Computing Systems X86 Assembly: Function Calls 1 Lecture Goals Challenges of supporting functions Providing information for the called function Function arguments and local variables Allowing the

### Type Conversion. and. Statements

and Statements Type conversion changing a value from one type to another Void Integral Floating Point Derived Boolean Character Integer Real Imaginary Complex no fractional part fractional part 2 tj Suppose

### switch case Logic Syntax Basics Functionality Rules Nested switch switch case Comp Sci 1570 Introduction to C++

Comp Sci 1570 Introduction to C++ Outline 1 Outline 1 Outline 1 switch ( e x p r e s s i o n ) { case c o n s t a n t 1 : group of statements 1; break ; case c o n s t a n t 2 : group of statements 2;

### ASTs, Objective CAML, and Ocamlyacc

ASTs, Objective CAML, and Ocamlyacc Stephen A. Edwards Columbia University Fall 2012 Parsing and Syntax Trees Parsing decides if the program is part of the language. Not that useful: we want more than

### Java Basic Programming Constructs

Java Basic Programming Constructs /* * This is your first java program. */ class HelloWorld{ public static void main(string[] args){ System.out.println( Hello World! ); A Closer Look at HelloWorld 2 This

### Chapter 11 Introduction to Programming in C

Chapter 11 Introduction to Programming in C C: A High-Level Language Gives symbolic names to values don t need to know which register or memory location Provides abstraction of underlying hardware operations

### Wednesday, October 15, 14. Functions

Functions Terms void foo() { int a, b;... bar(a, b); void bar(int x, int y) {... foo is the caller bar is the callee a, b are the actual parameters to bar x, y are the formal parameters of bar Shorthand:

### procedure definition (or declaration - some make a distinction, we generally won t), e.g., void foo(int x) {... }

Parameters Terminology: procedure invocation, e.g., (in different language notations) foo(a*8) x:=goo(19,a) call hoo() actual parameters, e.g., a*8 is an actual parameter of the above inv ocation of foo

### Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

Review Primitive Data Types & Variables int, long float, double boolean char String Mathematical operators: + - * / % Comparison: < > = == 1 1.3 Conditionals and Loops Introduction to Programming in

### CS558 Programming Languages

CS558 Programming Languages Fall 2016 Lecture 4a Andrew Tolmach Portland State University 1994-2016 Pragmatics of Large Values Real machines are very efficient at handling word-size chunks of data (e.g.

### Chapter 3:: Names, Scopes, and Bindings (cont.)

Chapter 3:: Names, Scopes, and Bindings (cont.) Programming Language Pragmatics Michael L. Scott Review What is a regular expression? What is a context-free grammar? What is BNF? What is a derivation?

### Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Control Structures Lecture 4 COP 3014 Fall 2017 September 18, 2017 Control Flow Control flow refers to the specification of the order in which the individual statements, instructions or function calls

### Concepts Introduced in Chapter 6

Concepts Introduced in Chapter 6 types of intermediate code representations translation of declarations arithmetic expressions boolean expressions flow-of-control statements backpatching EECS 665 Compiler

### Syntax and Parsing COMS W4115. Prof. Stephen A. Edwards Fall 2003 Columbia University Department of Computer Science

Syntax and Parsing COMS W4115 Prof. Stephen A. Edwards Fall 2003 Columbia University Department of Computer Science Lexical Analysis (Scanning) Lexical Analysis (Scanning) Goal is to translate a stream

### CSc 520. Principles of Programming Languages 25: Types Introduction

CSc 520 Principles of Programming Languages 25: Types Introduction Christian Collberg Department of Computer Science University of Arizona collberg@cs.arizona.edu Copyright c 2005 Christian Collberg April

### Chapter 8 Statement-Level Control Structure

Chapter 8 Statement-Level Control Structure To make programs more flexible and powerful: Some means of selecting among alternative control flow paths. Selection statement (conditional statements) Unconditional

### Names, Scopes, and Bindings II. Hwansoo Han

Names, Scopes, and Bindings II Hwansoo Han Scope Rules A scope is textual region where bindings are active A program section of maximal size Bindings become active at the entry No bindings change in the

### The C Language Reference Manual

The C Language Reference Manual Stephen A. Edwards Columbia University Summer 2014 Katsushika Hokusai, In the Hollow of a Wave off the Coast at Kanagawa, 1827 Part I The History of C C History Developed

### Compiler Theory. (GCC the GNU Compiler Collection) Sandro Spina 2009

Compiler Theory (GCC the GNU Compiler Collection) Sandro Spina 2009 GCC Probably the most used compiler. Not only a native compiler but it can also cross-compile any program, producing executables for

### Slide Set 1. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary

Slide Set 1 for ENCM 339 Fall 2016 Steve Norman, PhD, PEng Electrical & Computer Engineering Schulich School of Engineering University of Calgary September 2016 ENCM 339 Fall 2016 Slide Set 1 slide 2/43

### 6.001 Recitation 23: Register Machines and Stack Frames

6.001 Recitation 23: Register achines and Stack Frames RI: Gerald Dalley, dalleyg@mit.edu, 8 ay 2007 http://people.csail.mit.edu/dalleyg/6.001/sp2007/ iscellany apply: See the IT Scheme documentation for

### Variables and Java vs C++

Variables and Java vs C++ 1 What can be improved? (variables) public void godirection(string directionname) { boolean wenttoroom = false; for (Direction direction : currentroom.getdirections()) { if (direction.getdirectionname().equalsignorecase(directionname))

### Advanced use of the C language

Advanced use of the C language Content Why to use C language Differences from Java Object oriented programming in C Usage of C preprocessor Coding standards Compiler optimizations C99 and C11 Standards

### Ruby: Introduction, Basics

Ruby: Introduction, Basics Computer Science and Engineering College of Engineering The Ohio State University Lecture 4 Ruby vs Java: Similarities Imperative and object-oriented Classes and instances (ie

### Properties of an identifier (and the object it represents) may be set at

Properties of an identifier (and the object it represents) may be set at Compile-time These are static properties as they do not change during execution. Examples include the type of a variable, the value

### Software Analysis. Asymptotic Performance Analysis

Software Analysis Performance Analysis Presenter: Jonathan Aldrich Performance Analysis Software Analysis 1 Asymptotic Performance Analysis How do we compare algorithm performance? Abstract away low-level

### Tail Recursion: Factorial. Begin at the beginning. How does it execute? Tail recursion. Tail recursive factorial. Tail recursive factorial

Begin at the beginning Epressions (Synta) Compile-time Static Eec-time Dynamic Types Values (Semantics) 1. Programmer enters epression 2. ML checks if epression is well-typed Using a precise set of rules,

### Answer: Early binding generally leads to greater efficiency (compilation approach) Late binding general leads to greater flexibility

Quiz Review Q1. What is the advantage of binding things as early as possible? Is there any advantage to delaying binding? Answer: Early binding generally leads to greater efficiency (compilation approach)

### Concepts Introduced in Chapter 6

Concepts Introduced in Chapter 6 types of intermediate code representations translation of declarations arithmetic expressions boolean expressions flow-of-control statements backpatching EECS 665 Compiler

### Chapter 8. Fundamental Characteristics of Subprograms. 1. A subprogram has a single entry point

Fundamental Characteristics of Subprograms 1. A subprogram has a single entry point 2. The caller is suspended during execution of the called subprogram 3. Control always returns to the caller when the

### What is a compiler? Xiaokang Qiu Purdue University. August 21, 2017 ECE 573

What is a compiler? Xiaokang Qiu Purdue University ECE 573 August 21, 2017 What is a compiler? What is a compiler? Traditionally: Program that analyzes and translates from a high level language (e.g.,

### Parallel Programming with OpenMP. CS240A, T. Yang

Parallel Programming with OpenMP CS240A, T. Yang 1 A Programmer s View of OpenMP What is OpenMP? Open specification for Multi-Processing Standard API for defining multi-threaded shared-memory programs

### Programming Languages

CSE 130 : Spring 2011 Programming Languages Lecture 3: Crash Course Ctd, Expressions and Types Ranjit Jhala UC San Diego A shorthand for function binding # let neg = fun f -> fun x -> not (f x); # let

### Subprograms: Arguments

Subprograms: Arguments ICS312 Machine-Level and Systems Programming Henri Casanova (henric@hawaii.edu) Activation Records The stack is useful to store and rieve urn addresses, transparently managed via

### Fibonacci in Lisp. Computer Programming: Skills & Concepts (CP1) Programming Languages. Varieties of Programing Language

Fibonacci in Lisp Computer Programming: Skills & Concepts (CP1) Programming Languages (defun fibonacci (n) (if (or (= n 0) (= n 1)) 1 (+ (fibonacci (- n 1)) (fibonacci (- n 2))))) 22nd November 2010 defun-

### Chapter 11 Introduction to Programming in C

Chapter 11 Introduction to Programming in C Original slides from Gregory Byrd, North Carolina State University Modified slides by Chris Wilcox, Colorado State University C: A High-Level Language! Gives

### CSc 520 Principles of Programming Languages. Questions. rocedures as Control Abstractions... 30: Procedures Introduction

Procedures as Control Abstractions CSc 520 Principles of Programming Languages 30: Procedures Introduction Christian Collberg collberg@cs.arizona.edu Department of Computer Science University of Arizona

### An ANTLR Grammar for Esterel

An ANTLR Grammar for Esterel COMS W4115 Prof. Stephen A. Edwards Fall 2005 Columbia University Department of Computer Science ANTLR Esterel.g class EsterelParser extends Parser; file : expr EOF!; class

### CS 137 Part 2. Loops, Functions, Recursion, Arrays. September 22nd, 2017

CS 137 Part 2 Loops, Functions, Recursion, Arrays September 22nd, 2017 Loops We will finish this week with looping statements We already discussed one such structure, namely while loops. while (expr) statement

### CSCI312 Principles of Programming Languages!

CSCI312 Principles of Programming Languages! Scope Xu Liu ! 4.1 Syntactic Issues! 4.2 Variables! 4.3 Scope! 4.4 Symbol Table! 4.5 Resolving References! 4.6 Dynamic Scoping! 4.7 Visibility! 4.8 Overloading!

### Computer Science 324 Computer Architecture Mount Holyoke College Fall Topic Notes: MIPS Instruction Set Architecture

Computer Science 324 Computer Architecture Mount Holyoke College Fall 2009 Topic Notes: MIPS Instruction Set Architecture vonneumann Architecture Modern computers use the vonneumann architecture. Idea:

### News and information! Review: Java Programs! Feedback after Lecture 2! Dead-lines for the first two lab assignment have been posted.!

True object-oriented programming: Dynamic Objects Reference Variables D0010E Object-Oriented Programming and Design Lecture 3 Static Object-Oriented Programming UML" knows-about Eckel: 30-31, 41-46, 107-111,

### Implementing Subprograms

1 Implementing Subprograms CS 315 Programming Languages Pinar Duygulu Bilkent University CS315 Programming Languages Pinar Duygulu The General Semantics of Calls and Returns 2 The subprogram call and return

### Informatica 3 Syntax and Semantics

Informatica 3 Syntax and Semantics Marcello Restelli 9/15/07 Laurea in Ingegneria Informatica Politecnico di Milano Introduction Introduction to the concepts of syntax and semantics Binding Variables Routines

### So what does studying PL buy me?

So what does studying PL buy me? Enables you to better choose the right language but isn t that decided by libraries, standards, and my boss? Yes. Chicken-and-egg. My goal: educate tomorrow s tech leaders

### Intermediate representations IR #1: CPS/L 3. Code example. Advanced Compiler Construction Michel Schinz

Intermediate representations Intermediate representations Advanced Compiler Construction Michel Schinz 2016 03 03 The term intermediate representation (IR) or intermediate language designates the data-structure(s)

### Deep C (and C++) by Olve Maudal

Deep C (and C++) by Olve Maudal http://www.noaanews.noaa.gov/stories2005/images/rov-hercules-titanic.jpg Programming is hard. Programming correct C and C++ is particularly hard. Indeed, it is uncommon

### Advances in Programming Languages: Exam preparation and exam questions

Advances in Programming Languages: Exam preparation and exam questions Stephen Gilmore The University of Edinburgh March 24, 2006 Examinations What is the purpose of examinations? 1. To test understanding.

### Compiler Structure. Data Flow Analysis. Control-Flow Graph. Available Expressions. Data Flow Facts

Compiler Structure Source Code Abstract Syntax Tree Control Flow Graph Object Code CMSC 631 Program Analysis and Understanding Fall 2003 Data Flow Analysis Source code parsed to produce AST AST transformed

### LECTURE 3. Compiler Phases

LECTURE 3 Compiler Phases COMPILER PHASES Compilation of a program proceeds through a fixed series of phases. Each phase uses an (intermediate) form of the program produced by an earlier phase. Subsequent

### Iteration. Side effects

Computer programming Iteration. Side effects Marius Minea marius@cs.upt.ro 17 October 2017 Assignment operators We ve used the simple assignment: lvalue = expression lvalue = what can be on the left of

### CPSC 213. Introduction to Computer Systems. Procedures and the Stack. Unit 1e

CPSC 213 Introduction to Computer Systems Unit 1e Procedures and the Stack 1 Readings for Next 3 Lectures Textbook Procedures - 3.7 Out-of-Bounds Memory References and Buffer Overflow - 3.12 2 Local Variables

### HANDLING NONLOCAL REFERENCES

SYMBOL TABLE A symbol table is a data structure kept by a translator that allows it to keep track of each declared name and its binding. Assume for now that each name is unique within its local scope.

### Assembly Language Programming. CPSC 252 Computer Organization Ellen Walker, Hiram College

Assembly Language Programming CPSC 252 Computer Organization Ellen Walker, Hiram College Instruction Set Design Complex and powerful enough to enable any computation Simplicity of equipment MIPS Microprocessor