COP4020 Programming Languages. Subroutines and Parameter Passing Prof. Robert van Engelen

Similar documents
COP4020 Programming Languages. Subroutines and Parameter Passing Prof. Robert van Engelen

Chapter 9. Pointers and Dynamic Arrays. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

COP4020 Programming Languages. Compilers and Interpreters Prof. Robert van Engelen

CS 11 C track: lecture 1

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

Chapter 11. Friends, Overloaded Operators, and Arrays in Classes. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Python Programming: An Introduction to Computer Science

CMPT 125 Assignment 2 Solutions

Pseudocode ( 1.1) Analysis of Algorithms. Primitive Operations. Pseudocode Details. Running Time ( 1.1) Estimating performance

Running Time. Analysis of Algorithms. Experimental Studies. Limitations of Experiments

Running Time ( 3.1) Analysis of Algorithms. Experimental Studies. Limitations of Experiments

Analysis of Algorithms

What are we going to learn? CSC Data Structures Analysis of Algorithms. Overview. Algorithm, and Inputs

Outline and Reading. Analysis of Algorithms. Running Time. Experimental Studies. Limitations of Experiments. Theoretical Analysis

Classes and Objects. Again: Distance between points within the first quadrant. José Valente de Oliveira 4-1

Chapter 5. Functions for All Subtasks. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Data Structures and Algorithms. Analysis of Algorithms

Last class. n Scheme. n Equality testing. n eq? vs. equal? n Higher-order functions. n map, foldr, foldl. n Tail recursion

Analysis Metrics. Intro to Algorithm Analysis. Slides. 12. Alg Analysis. 12. Alg Analysis

Analysis of Algorithms

Linked Lists 11/16/18. Preliminaries. Java References. Objects and references. Self references. Linking self-referential nodes

Chapter 10. Defining Classes. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

High-Order Language APPLICATION LEVEL HIGH-ORDER LANGUAGE LEVEL ASSEMBLY LEVEL OPERATING SYSTEM LEVEL INSTRUCTION SET ARCHITECTURE LEVEL

CIS 121 Data Structures and Algorithms with Java Spring Stacks, Queues, and Heaps Monday, February 18 / Tuesday, February 19

From last week. Lecture 5. Outline. Principles of programming languages

Computers and Scientific Thinking

How do we evaluate algorithms?

A graphical view of big-o notation. c*g(n) f(n) f(n) = O(g(n))

Basic allocator mechanisms The course that gives CMU its Zip! Memory Management II: Dynamic Storage Allocation Mar 6, 2000.

COP4020 Programming Languages. Names, Scopes, and Bindings Prof. Robert van Engelen

Chapter 8. Strings and Vectors. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Programming with Shared Memory PART II. HPC Spring 2017 Prof. Robert van Engelen

Recursion. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Review: Method Frames

Chapter 8. Strings and Vectors. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Abstract. Chapter 4 Computation. Overview 8/13/18. Bjarne Stroustrup Note:

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Behavioral Modeling in Verilog

Lecture 1: Introduction and Strassen s Algorithm

implement language system

Homework 1 Solutions MA 522 Fall 2017

CIS 121 Data Structures and Algorithms with Java Spring Stacks and Queues Monday, February 12 / Tuesday, February 13

Python Programming: An Introduction to Computer Science

CMSC Computer Architecture Lecture 12: Virtual Memory. Prof. Yanjing Li University of Chicago

Overview. Chapter 18 Vectors and Arrays. Reminder. vector. Bjarne Stroustrup

n Haskell n Syntax n Lazy evaluation n Static typing and type inference n Algebraic data types n Pattern matching n Type classes

Today s objectives. CSE401: Introduction to Compiler Construction. What is a compiler? Administrative Details. Why study compilers?

Last Class. Announcements. Lecture Outline. Types. Structural Equivalence. Type Equivalence. Read: Scott, Chapters 7 and 8. T2 y; x = y; n Types

n Some thoughts on software development n The idea of a calculator n Using a grammar n Expression evaluation n Program organization n Analysis

Lecture Notes 6 Introduction to algorithm analysis CSS 501 Data Structures and Object-Oriented Programming

COSC 1P03. Ch 7 Recursion. Introduction to Data Structures 8.1

. Written in factored form it is easy to see that the roots are 2, 2, i,

Code Review Defects. Authors: Mika V. Mäntylä and Casper Lassenius Original version: 4 Sep, 2007 Made available online: 24 April, 2013

Examples and Applications of Binary Search

Major CSL Write your name and entry no on every sheet of the answer script. Time 2 Hrs Max Marks 70

n Maurice Wilkes, 1949 n Organize software to minimize errors. n Eliminate most of the errors we made anyway.

Analysis of Algorithms

Hash Tables. Presentation for use with the textbook Algorithm Design and Applications, by M. T. Goodrich and R. Tamassia, Wiley, 2015.

CSC 220: Computer Organization Unit 11 Basic Computer Organization and Design

why study sorting? Sorting is a classic subject in computer science. There are three reasons for studying sorting algorithms.

CSE 2320 Notes 8: Sorting. (Last updated 10/3/18 7:16 PM) Idea: Take an unsorted (sub)array and partition into two subarrays such that.

CS 111: Program Design I Lecture 16: Module Review, Encodings, Lists

CS200: Hash Tables. Prichard Ch CS200 - Hash Tables 1

UNIT 4C Iteration: Scalability & Big O. Efficiency

n The C++ template facility provides the ability to define n A generic facility allows code to be written once then

10/23/18. File class in Java. Scanner reminder. Files. Opening a file for reading. Scanner reminder. File Input and Output

CS 111: Program Design I Lecture 15: Objects, Pandas, Modules. Robert H. Sloan & Richard Warner University of Illinois at Chicago October 13, 2016

Package RcppRoll. December 22, 2014

Recursion. Recursion. Mathematical induction: example. Recursion. The sum of the first n odd numbers is n 2 : Informal proof: Principle:

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

Solutions to Final COMS W4115 Programming Languages and Translators Monday, May 4, :10-5:25pm, 309 Havemeyer

Chapter 6. I/O Streams as an Introduction to Objects and Classes. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Solution printed. Do not start the test until instructed to do so! CS 2604 Data Structures Midterm Spring, Instructions:

Chapter 3. More Flow of Control. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

University of Waterloo Department of Electrical and Computer Engineering ECE 250 Algorithms and Data Structures

Data Structures Week #9. Sorting

Polynomial Functions and Models. Learning Objectives. Polynomials. P (x) = a n x n + a n 1 x n a 1 x + a 0, a n 0

Data diverse software fault tolerance techniques

Chapter 24. Sorting. Objectives. 1. To study and analyze time efficiency of various sorting algorithms

CSC165H1 Worksheet: Tutorial 8 Algorithm analysis (SOLUTIONS)

top() Applications of Stacks

Chapter 2. C++ Basics. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

CS 111: Program Design I Lecture # 7: First Loop, Web Crawler, Functions

CSE 417: Algorithms and Computational Complexity

COMP Parallel Computing. PRAM (1): The PRAM model and complexity measures

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

CS 111: Program Design I Lecture 15: Modules, Pandas again. Robert H. Sloan & Richard Warner University of Illinois at Chicago March 8, 2018

Project 2.5 Improved Euler Implementation

CS211 Fall 2003 Prelim 2 Solutions and Grading Guide

Chapter 1. Introduction to Computers and C++ Programming. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Inductive Definition to Recursive Function

Lecture 5. Counting Sort / Radix Sort

IMP: Superposer Integrated Morphometrics Package Superposition Tool

Sorting in Linear Time. Data Structures and Algorithms Andrei Bulatov

6.854J / J Advanced Algorithms Fall 2008

Overview. Common tasks. Observation. Chapter 20 The STL (containers, iterators, and algorithms) 8/13/18. Bjarne Stroustrup

Priority Queues. Binary Heaps

CIS 121. Introduction to Trees

Ones Assignment Method for Solving Traveling Salesman Problem

DATA STRUCTURES. amortized analysis binomial heaps Fibonacci heaps union-find. Data structures. Appetizer. Appetizer

Big-O Analysis. Asymptotics

Transcription:

COP4020 Programmig Laguages Subrouties ad Parameter Passig Prof. Robert va Egele

Overview Parameter passig modes Subroutie closures as parameters Special-purpose parameters Fuctio returs COP4020 Fall 2016 2

Parameters First some defiitios Formal parameters Lisp: (lambda (a b) (/ (+ a b))) C fuctio: float ave(float a, float b) { retur (a+b)/2.0; } Versus actual parameters Lisp fuctio argumets: (ave x 10.0) C fuctio argumets: ave(x, 10.0) Versus operads (of operators ad special forms) Lisp special forms: (if flag yes o ) C operators: x > 0 && flag Operad hadlig ofte depeds o the type of built-i operator, e.g. special forms ad operators with short-circuit evaluatio COP4020 Fall 2016 3

Parameter Passig Parameter passig modes I I/out Out Parameter passig mechaisms Call by value (i) Call by referece (i+out) Call by result (out) Call by value/result (i+out) Call by ame (i+out) Differet mechaisms used by C, Fortra, Pascal, C++, Java, Ada (ad Algol 60) COP4020 Fall 2016 4

Parameter Passig i C Call by value parameter passig oly Actual parameter is evaluated ad its value assiged to the formal parameter A formal parameter i the fuctio body behaves as a local variable For example: it fac(it ) { if ( < 0) = 0; retur? *fac(-1) : 1; } Passig poiters allows the values of actuals to be modified For example: swap(it *a, it *b) { it t = *a; *a = *b; *b = t; } A fuctio call should explicitly pass poiters, e.g. swap(&x, &y); Arrays ad poiters are exchageable i C A array is automatically passed as a poiter to the array COP4020 Fall 2016 5

Parameter Passig i Fortra Call by referece parameter passig oly If the actual parameter is a l-value (e.g. a variable) its referece is passed to the subroutie If the actual parameter is a r-value (e.g. the value of a expressio) it is assiged to a hidde temporary variable whose referece is passed to the subroutie For example SUBROUTINE SHIFT(A, B, C) INTEGER A, B, C A = B B = C END For example, SHIFT(X, Y, 0) assigs Y to X, ad Y is set to 0 For example, SHIFT(X, 2, 3) assigs 2 to X ad the assigmet to B i the subroutie has o effect, but i Fortra IV this was ot hadled correctly! COP4020 Fall 2016 6

Parameter Passig i Pascal Call by value ad call by referece parameter passig Call by value is similar to C Call by referece: idicated with var qualifier i argumet list For example procedure swap(var a:iteger, var b:iteger) var t; begi t := a; a := b; b := t ed where the var parameters a ad b are passed by referece Programs ca suffer from uecessary data duplicatio overhead Whe a big array is passed by value the etire array is copied! Passig large arrays by referece avoids copy overhead But o clear distictio betwee i-mode or i/out-mode ay loger COP4020 Fall 2016 7

Parameter Passig i C++ Call by value ad call by referece parameter passig Call by value is similar to C Call by referece: use referece (&) operator For example: swap(it &a, it &b) { it t = a; a = b; b = t; } where the referece parameters a ad b are passed by referece Arrays are automatically passed by referece (like i C) Big objects should be passed by referece istead of by value To protect data from modificatio whe passed by referece, use cost, i.e. make it a i-mode parameter For example: store_record_i_file(cost huge_record &r) {... } Compiler will prohibit modificatios of object cost parameters (e.g. poiters) are also supported i ANSI C COP4020 Fall 2016 8

Parameter Passig by Sharig Call by sharig: parameter passig of variables i the referece model Referece model: variables are refereces to (shared) values Smalltalk, Lisp, ML, Clu, ad Java (partly) adopt the referece model of variables The value of the variable is passed as actual argumet, which i fact is a poiter to the (shared) value Essetially this is pass by value of the variable! Java uses both pass by value ad pass by sharig Variables of primitive built-i types are passed by value Class istaces are passed by sharig COP4020 Fall 2016 9

Parameter Passig i Ada I-mode parameters ca be read but ot writte i the subroutie Call by value Out-mode parameters ca be writte but ot read i the subroutie (Ada 95 allows read) Call by result, which uses a local variable to which the writes are made The resultig value is copied to the actual parameter to pass the value out whe the subroutie returs I-out-mode parameters ca be read ad writte i the subroutie Call by value/result uses a local variable that is iitialized by assigig the actual parameter's value to it The resultig value is copied to the actual parameter to pass the value out whe the subroutie returs Call by value, call by result, ad call by value/result parameter passig implemets i, out, ad i/out parameters, respectively Dager ahead: may use call by referece implemetatio for passig oscalars i/out (e.g. records ad arrays) to avoid copyig large objects! COP4020 Fall 2016 10

Parameter Passig i Ada: Example For example procedure shift(a:out iteger, b:i out iteger, c:i iteger) is begi a := b; b := c; ed shift; Here, a is passed out, b is passed i ad out, ad c is passed i COP4020 Fall 2016 11

Parameter Passig i Ada (cot d) The Ada compiler geerates specific code for the example shift procedure for i, out, ad i/out parameters to implemet call by value (i), call by result (out), ad call by value/result (i/out), which is similar to the followig C fuctio: void shift(it *a, it *b, it c) { it tmpa, tmpb = *b, tmpc = c; // copy iput values at begi } tmpa = tmpb; tmpb = tmpc; // perform operatios o temps *a = tmpa; *b = tmpb; // copy result values out before retur Temps are iitialized, operated o, ad copied to out mode parameters This is more efficiet tha pass by referece, because it avoids repeated poiter idirectio to access parameter values The Ada compiler may decide to use call by referece for passig oscalars (e.g. records ad arrays) for memory access optimizatio Okay for i-mode, because the parameter may ot be writte Okay for out ad i-out modes, sice the parameter is writte ayway COP4020 Fall 2016 12

Parameter Passig ad Aliasig A alias is a variable or formal parameter that refers to the same value as aother variable or formal parameter Example variable aliases i C++: it i, &j = i; // j refers to i (is a alias for i) i = 2; j = 3; cout << i; // prits 3 Example parameter aliases i C++: shift(it &a, it &b, cost it &c) { a = b; b = c; } The result of shift(x, y, x) is that x is set to y but y is uchaged Example mixig of variable ad parameter aliases i C++: it sum = 0; score(it &total, it val) { sum += val; total += val; } The result of score(sum, 7) is that sum is icremeted by 14 COP4020 Fall 2016 13

Parameter Passig ad Aliasig (cot d) Java adopts referece model of variables ad call by sharig Watch out for aliases, sice i referece model all assigmets create aliases Ada forbids parameter aliases Allows compiler to choose call by referece with the same effect as call by result But most compilers do t check ad the resultig program behavior is udefied COP4020 Fall 2016 14

Parameter Passig i Algol 60 Call by ame parameter passig by default, also call by value Passes actual argumets such as expressios ito the subroutie body for (re)evaluatio (reevaluatio doe via code thuks ) Jese's device utilizes call by ame: real procedure sum(expr, i, low, high); value low, high; low ad high are passed by value real expr; expr ad i are passed by ame iteger i, low, high; begi real rt; rt := 0; for i := low step 1 util high do rt := rt + expr; sum := rt ed sum the value of expr depeds o the value of i retur value by assigig to fuctio ame y := sum(3*x*x-5*x+2, x, 1, 10) calculates 10 y = Σ 3x 2-5x+2 x=1 COP4020 Fall 2016 15

Macro Expasio C/C++ macros (also called defies) adopt a form of call by ame For example #defie max(a,b) ( (a)>(b)? (a) : (b) ) Macro expasio is applied to the program source text ad amouts to the substitutio of the formal parameters with the actual parameters i the macro For example max(+1, m) is replaced by ((+1)>(m)?(+1):(m)) Note: formal parameters are ofte parethesized to avoid sytax problems whe expadig Similar to call by ame, actual parameters are re-evaluated each time the formal parameter is used Watch out for re-evaluatio of fuctio calls i actual parameters, for example max(somefuc(),0) results i the evaluatio of somefuc() twice if it returs a value >0 COP4020 Fall 2016 16

Parameter Passig Issues Call by ame problem: hard to write a swap routie that works: procedure swap(a, b) iteger a, b, t; begi t := a; a := b; b := t ed swap Cosider swap(i, a[i]), which executes: t := i i := a[i] this chages i a[i] := t assigs t to wrog array elemet COP4020 Fall 2016 17

Parameter Passig Issue (cot d) Call by value/result problem: behaves differetly compared to call by referece i the presece of aliases (that s why Ada forbids it) For example: procedure shift(a:out iteger, b:i out iteger, c:i iteger) is begi a := b; b := c; ed shift; Whe shift(x,x,0) is called by referece the resultig value of x is 0 Whe shift(x,x,0) is called by value/result the resultig value of x is either uchaged or 0 (because the order of copyig out mode parameters is uspecified) COP4020 Fall 2016 18

Coformat Arrays Some laguages support coformat arrays (or ope arrays) Examples: Ada, Stadard Pascal, Modula-2 Pascal arrays are types with embedded costat array bouds Arrays have fixed shape ad size Problem whe for example sortig arrays of differet sizes because sort procedure accepts oe type of array with oe size oly Array parameters i Stadard Pascal are coformat ad array size is ot fixed at compile-time For example: fuctio sum(a : array[low..high : iteger] of real) : real... Fuctio sum accepts real typed arrays ad low ad high act like formal parameters that are set to the lower ad upper boud idex of the actual array parameter C passes oly poiters to arrays to fuctios ad array size has to be determied usig some other meas (e.g. as aother parameter) COP4020 Fall 2016 19

Closures as Parameters Recall that a subroutie closure is a referece to a subroutie together with its referecig eviromet Stadard Pascal, Ada 95, Modula-2+3 fully support passig of subrouties as closures Stadard Pascal example: procedure apply_to_a(fuctio f(:iteger) : iteger; var A : array [low..high : iteger] of iteger); var i : iteger; begi for i := low to high do A[i] := f(a[i]) ed C/C++ supports fuctio poiters ad lambdas (C++11) Lambdas ca capture a referece eviromet Fuctio poiters are simplistic, for example: void apply_to_a(it (*f)(it), it A[], it A_size) { it i; for (i = 0; i < A_size; i++) A[i] = f(a[i]); } COP4020 Fall 2016 20

Default Parameters Ada, C++, Commo Lisp, ad Fortra 90 support default parameters A default parameter is a formal parameter with a default value Whe the actual parameter value is omitted i a subroutie call, the user-specified default value is used Example i C++: void prit_um(it, it base = 10)... A call to prit_um(35) uses default value 10 for base as if prit_um(35,10) was called Example i Ada: procedure put(item : i iteger; width : i field := default_width; base : i umber_base := 10) is... A call to put(35) uses default values for the width ad base parameters COP4020 Fall 2016 21

Positioal Versus Named Parameters Positioal parameters: the order of formal ad actual argumets is fixed All programmig laguages adopt this atural covetio Named parameter: (also called keyword parameter) explicitly bids the actual parameter to the formal parameter Ada, Modula-3, Commo Lisp, ad Fortra 90 For example i Ada: put(item => 35, base => 8); this "assigs" 35 to item ad 8 to base, which is the same as: put(base => 8, item => 35); ad we ca mix positioal ad ame parameters as well: put(35, base => 8); Pro: documetatio of parameter purpose Pro: allows default parameters aywhere i formal parameter list, whereas with positioal parameters the use of default parameters is restricted to the last parameter(s) oly, because the compiler caot tell which parameter is optioal i a subroutie ivocatio COP4020 Fall 2016 22

Variable Argumet Lists C,C++, ad Commo Lisp are uusual i that they allow defiig subrouties that take a variable umber of argumets Example i C: #iclude <stdarg.h> it plus(it um,...) { it sum; va_list args; // declare list of argumets va_start(args, um); // iitialize list of argumets for (it i=0; i<um; i++) sum += va_arg(args, it); // get ext argumet (assumed to be it) va_ed(args); // clea up list of argumets retur sum; } Fuctio plus adds a set of itegers, where the umber of itegers is the first parameter to the fuctio: plus(4,3,2,1,4) is 10 Used i the pritf ad scaf text formattig fuctios i C Variable umber of argumets i C ad C++ is ot type safe as parameter types are ot checked I Commo Lisp, oe ca write (+ 3 2 1 4) to add the itegers COP4020 Fall 2016 23

Fuctio Returs Some programmig laguages allow a fuctio to retur ay type of data structure, except maybe a subroutie (requires first-class subrouties) Modula-3 ad Ada allow a fuctio to retur a subroutie as a closure C ad C++ allow fuctios to retur poiters to fuctios (o closures) Some laguages use special variable to hold fuctio retur value Example i Pascal: fuctio max(a : iteger; b : iteger) : iteger; begi if a>b the max := a else max := b ed There is o retur statemet, istead the fuctio returs with the value of max whe it reaches the ed The subroutie frame reserves a slot for the retur value ayway, so these laguages make the slot explicitly available COP4020 Fall 2016 24

Fuctio Returs (cot d) Ada, C, C++, Java, ad other more moder laguages typically use a explicit retur statemet to retur a value from a fuctio Example i C: it max(it a, it b) { if (a>b) retur a; else retur b; } Programmers may eed a temporary variable for icremetal operatios o the retur value For example: it fac(it ) { it ret = 1; for (i = 2; i <= ; i++) ret *= i; retur ret; } Wastes time copyig the temporary variable value ito retur slot of subroutie frame o the stack COP4020 Fall 2016 25