Unformatted text preview:

78CS 538 Spring 2008©What Parameter Modes doProgramming Languages Use?• C: Value mode except for arrays whichpass a pointer to the start of the array.• C++: Allows reference as well as valuemodes. E.g.,int f(int a, int& b)• C#: Allows result (out) as well asreference and value modes. E.g.,int g(int a, out int b)• Java: Scalar types (int, float, char,etc.) are passed by value; objects arepassed by reference (references toobjects are passed by value).• Fortran: Reference (even forconstants!)• Ada: Value/result, reference, andreadonly are used.79CS 538 Spring 2008©Examplevoid p(value int a, reference int b, name int c) { a=1; b=2; print(c)}int i=3, j=3, k[10][10];p(i,j,k[i][j]);What element of k is printed?• The assignment to a does notaffect i, since a is a valueparameter.• The assignment to b does affect j,since b is a reference parameter.• c is a name parameter, so it isevaluated whenever it is used. Inthe print statement k[i][j] isprinted. At that point i=3 and j=2,so k[3][2] is printed.80CS 538 Spring 2008©Why are there so ManyDifferent Parameter Modes?Parameter modes reflectdifferent views on howparameters are to be accessed,as well as different degrees ofefficiency in accessing andusing parameters.• Call by value protects the actualparameter value. No matter whatthe subprogram does, theparameter can’t be changed.• Call by reference allows immediateupdates to the actual parameter.• Call by readonly protects the actualparameter and emphasizes the“constant” nature of the formalparameter.81CS 538 Spring 2008©• Call by value/result allows actualparameters to change, but treats acall as a single step (assignparameter values, execute thesubprogram’s body, updateparameter values).• Call by name delays evaluation ofan actual parameter until it isactually needed (which may benever).82CS 538 Spring 2008©Call by NameCall by name is a special kindof parameter passing mode. Itallows some calls to completethat otherwise would fail.Considerf(i,j/0)Normally, when j/0 isevaluated, a divide faultterminates execution. Ifj/0 ispassed by name, the division isdelayed until the parameter isneeded, which may be never.Call by name also allowsprogrammers to create someinteresting solutions to hardprogramming problems.83CS 538 Spring 2008©Consider the conditionalexpression found in C, C++,and Java:(cond ? value1 : value2)What if we want to implementthis as a function call:condExpr(cond,value1,value2) { if (cond) return value1; else return value2; }With most parameter passingmodes this implementationwon’t work! (Why?)But ifvalue1 and value2 arepassed by name, theimplementation is correct.84CS 538 Spring 2008©Call by Name and LazyEvaluationCall by name has much of theflavor of lazy evaluation. Withlazy evaluation, you don’tcompute a value but rather asuspension—a function that willprovide a value when called.This can be useful when we needto control how much of acomputation is actuallyperformed.Consider an infinite list ofintegers. Mathematically it isrepresented as 1, 2, 3, ...How do we compute a datastructure that represents aninfinite list?85CS 538 Spring 2008©The obvious computationinfList(int start) { return list(start, infList(start+1)); }doesn’t work. (Why?)A less obvious implementation,using suspensions, does work:infList(int start) { return list(start, function() { return infList(start+1); });}Now, whenever we are given aninfinite list, we get two things: thefirst integer in the list and asuspension function. When called,this function will give you the restof the infinite list (again, onemore value and anothersuspension function).86CS 538 Spring 2008©The whole list is there, but only asmuch as you care to access isactually computed.87CS 538 Spring 2008©Eager Parameter EvaluationSometimes we want parametersevaluated eagerly—as soon asthey are known.Consider a sorting routine thatbreaks an array in half, sortseach half, and then mergestogether the two sorted halves(this is a merge sort).In outline form it is:sort(inputArray) { ...merge(sort(leftHalf(inputArray)), sort(rightHalf(inputArray)));}This definition lends itselfnicely to parallel evaluation:The two halves of an inputarray can be sorted in parallel.Each of these two halves can88CS 538 Spring 2008©again be split in two, allowingparallel sorting of four quarter-sized arrays, then leading to 8sorts of 1/8 sized arrays, etc.But,to make this all work, the twoparameters to merge must beevaluated eagerly, rather thanin sequence.89CS 538 Spring 2008©Type EquivalenceProgramming languages usetypes to describe the values adata object may hold and theoperations that may beperformed.By checking the types of values,potential errors in expressions,assignments and calls may beautomatically detected. Forexample, type checking tells usthat123 + "123"is illegal because addition is notdefined for an integer, stringcombination.Type checking is usually done atcompile-time; this is static typing.90CS 538 Spring 2008©Type-checking may also be doneat run-time; this is dynamictyping.A program is type-safe if it isimpossible to apply an operationto a value of the wrong type. In atype-safe language, plus is nevertold to add an integer to a string,because its definition does notallow that combination ofoperands. In type-safe programsan operator can still see an illegalvalue (e.g., a division by zero),but it can’t see operands of thewrong type.A strongly-typed programminglanguage forbids the execution oftype-unsafe programs.Weakly-typed programminglanguages allow the execution ofpotentially type-unsafe programs.91CS 538 Spring 2008©The question reduces to whetherthe programming language allowsprogrammers to “break” the typerules, either knowingly orunknowingly.Java is strongly typed; type errorspreclude execution. C and C++are weakly typed; you can breakthe rules if you wish. Forexample: int i; int* p; p = (int *) i * i;Now p may be used as an integerpointer though multiplicationneed not produce valid integerpointers.If we are going to do typechecking in a program, we mustdecide whether two types, T1 andT2 are equivalent; that is, whetherthey be used interchangeably.92CS 538 Spring 2008©There are two major approachesto type equivalence:Name Equivalence:Two types are equivalent if andonly if they refer to exactly thesame type declaration.For example,type PackerSalaries = int[100]; type AssemblySizes = int[100]; PackerSalaries


View Full Document

UW-Madison COMPSCI 538 - Lecture Notes

Download Lecture Notes
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Lecture Notes and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Lecture Notes 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?