constructs for data organization and program control, scope, binding, and parameter passing....

21
Constructs for Data Constructs for Data Organization and Organization and Program Control, Program Control, Scope, Binding, and Scope, Binding, and Parameter Passing. Parameter Passing. Expression Evaluation Expression Evaluation

Upload: louise-robbins

Post on 19-Jan-2018

223 views

Category:

Documents


0 download

DESCRIPTION

Recall: Asymptotic Analysis – Big (O)  As a programmer, you often have a choice of data structures and algorithms. Choosing involves two factors  Time Complexity: how much time  Space Complexity: how much storage  Big Oh relates to an upper bound on complexity meaning the worst amount of time/space an algorithm could take.

TRANSCRIPT

Page 1: Constructs for Data Organization and Program Control, Scope, Binding, and Parameter Passing. Expression Evaluation

Constructs for Data Constructs for Data Organization and Program Organization and Program

Control, Scope, Binding, and Control, Scope, Binding, and Parameter Passing. Parameter Passing.

Expression EvaluationExpression Evaluation

Page 2: Constructs for Data Organization and Program Control, Scope, Binding, and Parameter Passing. Expression Evaluation

Constructs for Data OrganizationConstructs for Data Organization

Data Structures: Used to implement a Data Structures: Used to implement a collection of objects.collection of objects. ArraysArrays Linked Lists Linked Lists StacksStacks RecursionRecursion

Page 3: Constructs for Data Organization and Program Control, Scope, Binding, and Parameter Passing. Expression Evaluation

Recall: Asymptotic Analysis – Recall: Asymptotic Analysis – Big (O)Big (O)

As a programmer, you often have a choice As a programmer, you often have a choice of data structures and algorithms. of data structures and algorithms. Choosing involves two factorsChoosing involves two factors Time Complexity: how much timeTime Complexity: how much time Space Complexity: how much storageSpace Complexity: how much storage

Big Oh relates to an upper bound on Big Oh relates to an upper bound on complexity meaning the worst amount of complexity meaning the worst amount of time/space an algorithm could take.time/space an algorithm could take.

Page 4: Constructs for Data Organization and Program Control, Scope, Binding, and Parameter Passing. Expression Evaluation

Continue: Data OrganizationContinue: Data Organization Sorted ListSorted List

Array vs. Array vs. Linked List Linked List ImplementationImplementation

OperationOperation ArrayArray Linked ListLinked List

Create empty listCreate empty list O(1)O(1) O(1)O(1)

Delete all list elementsDelete all list elements O(1)O(1) O(n)O(n)

Compute LengthCompute Length O(1)O(1) O(n)O(n)

Search for itemSearch for item O(log n)O(log n) O(n)O(n)

Access kth element in Access kth element in listlist

O(1)O(1) O(n)O(n)

Access next list elementAccess next list element O(1)O(1) O(1)O(1)

Access previous list Access previous list elementelement

O(1)O(1) O(n)O(n)

Insert/delete accessed Insert/delete accessed item item

O(n)O(n) O(1)O(1)

Page 5: Constructs for Data Organization and Program Control, Scope, Binding, and Parameter Passing. Expression Evaluation

Data Organization AlgorithmsData Organization AlgorithmsBinary Search Binary Search O(O(log log n)n)

TreesTrees Hight = floor( log2Hight = floor( log2nn ) ) Add & Delete O(logAdd & Delete O(lognn) )

QueuesQueues Add=Delete=O(1)Add=Delete=O(1)

Priority Queues Priority Queues OO(log(lognn) For tree structure; ) For tree structure; however however O(n)O(n) if the tree is if the tree is unballancedunballanced

Heaps ; based on the notion of a Heaps ; based on the notion of a complete treecomplete tree

Time for Extract Max Time for Extract Max =Insert=O(log=Insert=O(lognn) ; ) ;

Bubble, Selection, Insertion Bubble, Selection, Insertion SortsSorts

O(n2)O(n2) only suitable for small only suitable for small problemsproblems

Red-Black TreesRed-Black Trees O(log n)O(log n)

Page 6: Constructs for Data Organization and Program Control, Scope, Binding, and Parameter Passing. Expression Evaluation

Program ControlProgram Control Aspects of the language that control which Aspects of the language that control which

program statements get executed, and in program statements get executed, and in what order. Control Statements do not what order. Control Statements do not evaluate to a numeric value.evaluate to a numeric value.

ExamplesExamples If StatementsIf Statements While StatementsWhile Statements For StatementsFor Statements Break StatementBreak Statement

Page 7: Constructs for Data Organization and Program Control, Scope, Binding, and Parameter Passing. Expression Evaluation

ScopeScope

The scope of an identifier is the region of a The scope of an identifier is the region of a program source within which it represents program source within which it represents a certain thing (int, object, etc.). This a certain thing (int, object, etc.). This usually extends from the place where it is usually extends from the place where it is declared to the end of the smallest declared to the end of the smallest enclosing block (begin/end or enclosing block (begin/end or procedure/function body).procedure/function body).

Page 8: Constructs for Data Organization and Program Control, Scope, Binding, and Parameter Passing. Expression Evaluation

Examples of ScopeExamples of Scope Lexical Scope( or static scope): scope of Lexical Scope( or static scope): scope of

an identifier is fixed at compile time to an identifier is fixed at compile time to some region in the source code containing some region in the source code containing the identifiers declaration. This means the identifiers declaration. This means that an identifier is only accessible within that an identifier is only accessible within that region. that region. Int foo( )

{

int a;

a=3

return a;

}

Page 9: Constructs for Data Organization and Program Control, Scope, Binding, and Parameter Passing. Expression Evaluation

Dynamic Scope:Dynamic Scope: An identifier can be referred to, not only in An identifier can be referred to, not only in

the block where it is declared, but also in the block where it is declared, but also in any function or procedure called from any function or procedure called from within that block, even if the called within that block, even if the called procedure is declared outside the block. procedure is declared outside the block. Global Variable.Global Variable.

Int a;

main Foo()

{ int b;

a=5;

b=foo2() }

Int Foo2()

{

return a;

}

Page 10: Constructs for Data Organization and Program Control, Scope, Binding, and Parameter Passing. Expression Evaluation

Static/Dynamic BindingStatic/Dynamic Binding

Static Binding (AKA Early Binding): The Static Binding (AKA Early Binding): The compiler uses the type of variables to do compiler uses the type of variables to do the binding at the compile timethe binding at the compile time

Dynamic Binding(AKA Late Binding): the Dynamic Binding(AKA Late Binding): the decision is made at run time based on the decision is made at run time based on the type of the actual valuestype of the actual values

Page 11: Constructs for Data Organization and Program Control, Scope, Binding, and Parameter Passing. Expression Evaluation

Main Binding TechniquesMain Binding Techniques Early (static) binding, is the binding of functions in a program at Early (static) binding, is the binding of functions in a program at

compile timecompile time The program knows the type of the data for each The program knows the type of the data for each function called. For example:function called. For example:

AddRealNums (x, y) x & y are of type realAddRealNums (x, y) x & y are of type real

Late (dynamic) binding of the message selector to the appropriate Late (dynamic) binding of the message selector to the appropriate method at run timemethod at run time

The programmer doesn’t know the specific method The programmer doesn’t know the specific method that will be usedthat will be used

AddNumber(x, y) x & y are number objectsAddNumber(x, y) x & y are number objects

Page 12: Constructs for Data Organization and Program Control, Scope, Binding, and Parameter Passing. Expression Evaluation

Shape Class ExampleShape Class Example A display list in a graphic application.A display list in a graphic application. List Elements:List Elements: Object of subclasses of class shapeObject of subclasses of class shape

Triangles, rectangles etc.Triangles, rectangles etc. We want the list to contain elements of type Shape, but We want the list to contain elements of type Shape, but

each should be capable of preserving its own special each should be capable of preserving its own special properties.properties.

If we loop over the list and send each element in it a If we loop over the list and send each element in it a draw message, the element should respond according to draw message, the element should respond according to its dynamic type.its dynamic type.

Page 13: Constructs for Data Organization and Program Control, Scope, Binding, and Parameter Passing. Expression Evaluation

Static vs. Dynamic BindingStatic vs. Dynamic Binding Static binding: binding based on static typeStatic binding: binding based on static type

More efficientMore efficientLess flexibleLess flexible

Dynamic Binding:Dynamic Binding:More flexibleMore flexibleLess efficientLess efficient

Page 14: Constructs for Data Organization and Program Control, Scope, Binding, and Parameter Passing. Expression Evaluation

Parameter Passing MechanismsParameter Passing Mechanisms

Call-by-valueCall-by-value Call-by-referenceCall-by-reference Copy-restoreCopy-restore Call-by-nameCall-by-name Functions as ParametersFunctions as Parameters

Page 15: Constructs for Data Organization and Program Control, Scope, Binding, and Parameter Passing. Expression Evaluation

Term and DefinitionsTerm and Definitions Formal Parameter: specified (together with type) when Formal Parameter: specified (together with type) when

procedure is declared (AKA procedure is declared (AKA formalsformals)) Actual Parameters: values which are passed to a Actual Parameters: values which are passed to a

procedure at call site (AKA procedure at call site (AKA actualsactuals).). L-value: storage location represented by an expression L-value: storage location represented by an expression

(e.g. a register, a memory location, etc.)(e.g. a register, a memory location, etc.) R-value: value contained at the storage locationR-value: value contained at the storage location L- and r refer to the “left” and “right” side of an L- and r refer to the “left” and “right” side of an

assignment.assignment. Int factorial ( int n)

{

if (n == 0) return 1;

else return n * factorial (n – 1 );

}

Factorial ( 42 );

Formal

Actuals

Page 16: Constructs for Data Organization and Program Control, Scope, Binding, and Parameter Passing. Expression Evaluation

Call-by-valueCall-by-value A formal is treated the same as a local (i.e. storage is A formal is treated the same as a local (i.e. storage is

allocated on the stack or in a register)allocated on the stack or in a register) The caller evaluates the actuals and passes the result to The caller evaluates the actuals and passes the result to

the calleethe callee Operations on the formals do not affect values in the Operations on the formals do not affect values in the

stack frame of the caller, so the following will not work:stack frame of the caller, so the following will not work:

Void swap (int a, int b) {int temp;temp = a; a = b; b = temp;

}

Page 17: Constructs for Data Organization and Program Control, Scope, Binding, and Parameter Passing. Expression Evaluation

Call-by-referenceCall-by-reference Also known as: Also known as: call-by-address, call-by-locationcall-by-address, call-by-location The location of the actual is passed, rather then its The location of the actual is passed, rather then its

value:value:if the actual is a variable (i.e. corresponds to an if the actual is a variable (i.e. corresponds to an assignable location assignable location in memory) its address is in memory) its address is

passedpassed

if the actual is an expression, the expression is if the actual is an expression, the expression is evaluated to a temporary location and the address of evaluated to a temporary location and the address of that location is passed ( the compiler will warn you that location is passed ( the compiler will warn you since this is not what you usually want)since this is not what you usually want)

Operation on the formals do affect the values in the Operation on the formals do affect the values in the caller, so procedure swap now works:caller, so procedure swap now works:

Void swap (int& a, int& b) {int temp;temp = a; a = b; b = temp;

}

Page 18: Constructs for Data Organization and Program Control, Scope, Binding, and Parameter Passing. Expression Evaluation

Copy-restoreCopy-restore Also known as: Also known as: copy-in copy-out, value-resultcopy-in copy-out, value-result Combination of call-by-value and call-by-reference:Combination of call-by-value and call-by-reference:

The actuals are evaluated before the callThe actuals are evaluated before the call The expression having only r-values,The expression having only r-values, The expression having l-values are passed by referenceThe expression having l-values are passed by reference

Page 19: Constructs for Data Organization and Program Control, Scope, Binding, and Parameter Passing. Expression Evaluation

Call-by-NameCall-by-Name The evaluation of actuals is The evaluation of actuals is delayeddelayed until their use in until their use in

calleecallee Can be implemented by using parameterless evaluation Can be implemented by using parameterless evaluation

procedures (sometimes called thunks) that are created procedures (sometimes called thunks) that are created for each actual:for each actual:

Void foo( int a, int b ){

… a … b …}…Foo ( 1+2, 3 ) ;…

Int thunk_1( ) {return 1 + 2

}Int thunk_2( ) {

return 3;}Void foo( proc f, proc g) {

… p() … q() …}…Foo (thunk_1, thunk_2);…

Page 20: Constructs for Data Organization and Program Control, Scope, Binding, and Parameter Passing. Expression Evaluation

Functions as ParametersFunctions as Parameters A parameter to a function may be a function A parameter to a function may be a function

itself. Such a parameter is declared by writing itself. Such a parameter is declared by writing the name of the function’s return type (or void), the name of the function’s return type (or void), then the name of the parameter, and finally a then the name of the parameter, and finally a pair of parentheses(). Inside the parentheses is pair of parentheses(). Inside the parentheses is a list of the parameter types that the function a list of the parameter types that the function needs.needs.

Void apply ( void f( int& ), int data [ ], size_t n ){

size_t i ;

for ( i = 0; i < n; ++ i)f ( data [ i ] );

}

Function parameter

Page 21: Constructs for Data Organization and Program Control, Scope, Binding, and Parameter Passing. Expression Evaluation

ResourcesResources Introduction to Algorithms - CormenIntroduction to Algorithms - Cormen Data Structures and other objects using C++ - SavitchData Structures and other objects using C++ - Savitch http://ciips.ee.uwa.edu.au/~morris/Year2/PLDS210/ds_ToC.htmlhttp://ciips.ee.uwa.edu.au/~morris/Year2/PLDS210/ds_ToC.html http://www.cs.cornell.comhttp://www.cs.cornell.com http://www.csd.uu.se/kurs/oop/ht98/Lectures/D5/html/Dynamic_Bindhttp://www.csd.uu.se/kurs/oop/ht98/Lectures/D5/html/Dynamic_Bind

ing/sld019.htming/sld019.htm Applying Data Structures 2Applying Data Structures 2ndnd ed – T.G. Lewis ed – T.G. Lewis Compilers Construction ( Principles and Practice) - LoudenCompilers Construction ( Principles and Practice) - Louden