ice1341 programming languages spring 2005 lecture #10 lecture #10 in-young ko iko.at. icu.ac.kr...
TRANSCRIPT
ICE1341 ICE1341 Programming LanguagesProgramming Languages
Spring 2005Spring 2005
Lecture #10Lecture #10
In-Young Koiko .AT. icu.ac.kr
Information and Communications University (ICU)
Spring 2005 2 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
AnnouncementsAnnouncements
Midterm ExamMidterm Exam Time and LocationTime and Location
Monday April 4, 2005 4PM-6PMMonday April 4, 2005 4PM-6PM L401L401
CoverageCoverage Chapters 1, 3, 5 and 6Chapters 1, 3, 5 and 6 WWW Concepts and LanguagesWWW Concepts and Languages
Closed book and noteClosed book and note Midterm Project Report Due & PresentationMidterm Project Report Due & Presentation
Thursday April 14Thursday April 14thth
Spring 2005 3 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Scope RulesScope Rules
Last LectureLast Lecture
Spring 2005 4 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
This LectureThis Lecture
Data TypesData Types Primitive TypesPrimitive Types Character String Data TypesCharacter String Data Types User-defined Data TypesUser-defined Data Types ArraysArrays RecordsRecords UnionsUnions PointersPointers
Spring 2005 5 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Static vs. Dynamic ScopesStatic vs. Dynamic Scopes
Call Sequence: Call Sequence: MAIN calls BMAIN calls B B calls AB calls A A calls DA calls D
Program StructureProgram Structure
Call SequenceCall Sequence
The The reference environmentreference environment of a statement of a statement at D:at D:• Static scopingStatic scoping Variables defined in Variables defined in
D, A D, A andand main main• Dynamic scopingDynamic scoping Variables defined Variables defined
in in D, A, B D, A, B andand main main
Spring 2005 6 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Homework #4Homework #4
Write a simple Java program that includes:Write a simple Java program that includes: At least two At least two non-local variablesnon-local variables defined with defined with initializationinitialization At least two At least two static variablesstatic variables defined in different scopes defined in different scopes At least two At least two overwriting variablesoverwriting variables defined in different scopes defined in different scopes At least two accesses of At least two accesses of hidden variableshidden variables Two Two named constantsnamed constants, one with the , one with the static value bindingstatic value binding, and the , and the
other with the other with the dynamic value bindingdynamic value binding
Add commentsAdd comments to indicate where those variables are to indicate where those variables are Explain the Explain the static scopesstatic scopes of the variables of the variables Explain the Explain the lifetimeslifetimes of the variables of the variables Explain the Explain the reference environmentsreference environments of statements at of statements at
three different locations in the programthree different locations in the program
Due by April 4thDue by April 4th
Spring 2005 7 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Data TypesData Types
A A data typedata type defines a collection of defines a collection of data objectsdata objects and and a set of predefined a set of predefined operationsoperations on those objects on those objects Primitive Data TypesPrimitive Data Types: data types that are not defined in : data types that are not defined in
terms of other types (e.g., int, float, char)terms of other types (e.g., int, float, char) Structured Data TypesStructured Data Types: non-scalar data types that : non-scalar data types that
specify structured organizations of data of other types specify structured organizations of data of other types (e.g., arrays, records)(e.g., arrays, records)
Design issuesDesign issues for all data types: for all data types: What is the What is the syntaxsyntax of references to variables? of references to variables? What What operationsoperations are defined and how are they specified? are defined and how are they specified?
Spring 2005 8 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Primitive Data Types –Primitive Data Types –Numeric Types (1)Numeric Types (1)
IntegerInteger Its representation usually reflects the hardware (size, Its representation usually reflects the hardware (size,
notation – ones or notation – ones or twos complementtwos complement)) e.g., e.g., Java Java – byte, short, int, long; – byte, short, int, long; CC – unsigned int – unsigned int
Floating-pointFloating-point Model real numbers, but only as Model real numbers, but only as approximationsapproximations IEEE Floating-Point Standard 754IEEE Floating-Point Standard 754 format format e.g., Java – float, doublee.g., Java – float, double PrecisionPrecision: the accuracy of the fractional part of a value: the accuracy of the fractional part of a value RangeRange: a combination of the ranges of fractions and : a combination of the ranges of fractions and
exponentsexponents
Spring 2005 9 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
IEEE Floating Point FormatsIEEE Floating Point Formats
floatfloat
doubledouble
0<e<255, (-1)0<e<255, (-1)ss * 2 * 2e-127e-127 * 1.f * 1.f
Spring 2005 10
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Primitive Data Types –Primitive Data Types –Numeric Types (2)Numeric Types (2)
DecimalDecimal Store a fixed number of decimal digits (coded), with Store a fixed number of decimal digits (coded), with
decimal point at a fixed positiondecimal point at a fixed position e.g., e.g., BCD (Binary Coded Decimal)BCD (Binary Coded Decimal) Advantage: accuracy (e.g., 0.1 represented in BCD Advantage: accuracy (e.g., 0.1 represented in BCD
vs. Floating-point)vs. Floating-point) Disadvantages: limited range, wastes memoryDisadvantages: limited range, wastes memory
BooleanBoolean Could be implemented as bits, but often as bytesCould be implemented as bits, but often as bytes Advantage: readabilityAdvantage: readability
CharacterCharacter Stored as numeric codings (e.g., Stored as numeric codings (e.g., ASCIIASCII, , UnicodeUnicode))
* AW Lecture Notes
Spring 2005 11
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Character String TypesCharacter String Types
Character StringCharacter String: a sequence of characters: a sequence of characters Design issues:Design issues:
Is it a primitive type or just a special kind of array?Is it a primitive type or just a special kind of array?e.g., Java – the String class, C – character arrays (char *str)e.g., Java – the String class, C – character arrays (char *str)
Is the length of strings static or dynamic?Is the length of strings static or dynamic? Static length stringsStatic length strings – e.g., Java, Fortran – e.g., Java, Fortran Limited dynamic length stringsLimited dynamic length strings – e.g., C (sizeof vs. strlen) – e.g., C (sizeof vs. strlen) Dynamic length stringsDynamic length strings – e.g., JavaScript, Perl – e.g., JavaScript, Perl
Operations:Operations: AssignmentAssignment, , ComparisonComparison (e.g., strcmp, >), (e.g., strcmp, >),
CatenationCatenation (e.g., strcat, +), (e.g., strcat, +), Substring referenceSubstring reference, , Pattern matchingPattern matching (e.g., indexOf, (e.g., indexOf, matchesmatches))
* AW Lecture Notes
Spring 2005 12
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Implementation of String TypesImplementation of String Types
Static lengthStatic length - compile-time descriptor - compile-time descriptor Limited dynamic lengthLimited dynamic length - may need a - may need a run-time run-time
descriptordescriptor for length (C and C++ use ‘ for length (C and C++ use ‘\0\0’ to indicate the ’ to indicate the end of the string)end of the string)
Dynamic lengthDynamic length - need a run-time descriptor; - need a run-time descriptor; allocation/deallocationallocation/deallocation is the biggest implementation is the biggest implementation problemproblem
* AW Lecture Notes
Compile-time descriptor for static strings
Run-time descriptor for limited dynamic strings
Spring 2005 13
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
User-Defined Ordinal TypesUser-Defined Ordinal Types
An An ordinal typeordinal type is one in which the range of is one in which the range of possible values can be easily associated with the possible values can be easily associated with the set of set of positive integerspositive integerse.g., Java – int, char, booleane.g., Java – int, char, boolean
Enumeration TypesEnumeration Types: : user-defined ordinal typesuser-defined ordinal types in in which named constants (which named constants (enumeration constantsenumeration constants) ) are provided in the definitionare provided in the definitione.g., e.g., enumenum days { Mon, Tue, Wed, Thu, Fri, Sat, Sun }; days { Mon, Tue, Wed, Thu, Fri, Sat, Sun };
days myDay = Sat;days myDay = Sat; char *str = names[Tue];char *str = names[Tue];
C++, C#, Pascal, Ada support enumeration typesC++, C#, Pascal, Ada support enumeration types Improve Improve readabilityreadability and and reliabilityreliability (restricting ranges) (restricting ranges)
Spring 2005 14
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Design Issues of User-Defined Design Issues of User-Defined Ordinal TypesOrdinal Types
Reuse of constants (Reuse of constants (overloaded literalsoverloaded literals)) e.g., e.g., enumenum weekendDays { Sat, Sun }; weekendDays { Sat, Sun }; ? ? The type of an occurrence of a constant needs The type of an occurrence of a constant needs
to be determined to be determined based on its contextbased on its context Ada supports overloaded literalsAda supports overloaded literals
Coercion to integerCoercion to integer e.g., e.g., myDay++; myDay++; ??
myDay = 4;myDay = 4; ? ? myDate = (days)4;myDate = (days)4; ? ? C++ enumeration types are C++ enumeration types are coerced to integercoerced to integer
Spring 2005 15
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Subrange Types (Subtypes)Subrange Types (Subtypes)
Contiguous sequences of an ordinal typeContiguous sequences of an ordinal typee.g.1, e.g.1, subtypesubtype Index Index isis Integer Integer rangerange 1..100; 1..100;e.g.2,e.g.2, typetype Days Days isis ( Mon, Tue, Wed, Thu, Fri, Sat, Sun); ( Mon, Tue, Wed, Thu, Fri, Sat, Sun);
subtypesubtype Weekdays Weekdays isis Days Days rangerange Mon..Fri; Mon..Fri; Pascal and Ada support subrange typesPascal and Ada support subrange types Subtypes are not new types, just constrained Subtypes are not new types, just constrained
existing types (so they are compatible);existing types (so they are compatible);c.f., Derived Typesc.f., Derived Types e.g., e.g., typetype Derived_Int Derived_Int is newis new Integer Integer rangerange 1..100; 1..100;
subtypesubtype Subrange_Int Subrange_Int isis Integer Integer rangerange 1..100;1..100;
Enhance Enhance readabilityreadability and and reliabilityreliability
Spring 2005 16
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Array TypesArray Types
ArrayArray: an aggregate of : an aggregate of homogeneoushomogeneous data data elementselements in which an individual in which an individual element is element is identified by its position (identified by its position (subscriptsubscript or or indexindex))
IndexingIndexing: a mapping from indices to elements: a mapping from indices to elements e.g., e.g., A(2), A[2], *(A + 2)A(2), A[2], *(A + 2)
Subscript Types:Subscript Types: FORTRAN, C, Java – integer onlyFORTRAN, C, Java – integer only Pascal, Ada – any Pascal, Ada – any ordinal typeordinal type (integer, boolean, char, (integer, boolean, char,
enum)enum)
… …
00 11 n-1n-1 nn
An elementAn element
Subscripts (Indices)Subscripts (Indices)
A:A:
Spring 2005 17
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Categories of ArraysCategories of Arrays
Based on Based on subscript bindingsubscript binding and and binding to storagebinding to storage
Stack AreaStack Area(Local variables)(Local variables)
Static AreaStatic Area(Program code & non-local, (Program code & non-local,
static variables)static variables)
Heap AreaHeap Area(Dynamically (Dynamically
allocated/deallocated blocks)allocated/deallocated blocks)
A program space in A program space in the memorythe memory
……
… …
00 11 1818 1919
AAStatic Static (Fortran 77)(Fortran 77)
… …
00 11 n-1n-1 nn
AAStack-dynamicStack-dynamic(Ada, C)(Ada, C)
… …
00 11 1818 1919
AAFixed heap-dynamicFixed heap-dynamic
(Fortran 90, C, Java)(Fortran 90, C, Java)
… …
00 11 1818 1919
AAFixed stack-dynamic Fixed stack-dynamic
(C)(C)
… …
00 11 n-1n-1 xx
AAHeap-dynamicHeap-dynamic
(Perl, JavaScript)(Perl, JavaScript)
Spring 2005 18
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Other Design Issues of ArraysOther Design Issues of Arrays
Number of subscripts (Number of subscripts (DimensionDimension)) FORTRAN I allowed up to threeFORTRAN I allowed up to three FORTRAN 77 allows up to sevenFORTRAN 77 allows up to seven Others - no limitOthers - no limit
Array Initialization Array Initialization A list of valuesA list of values – e.g. (C), – e.g. (C), intint stuff [] = {2, 4, 6, 8}; stuff [] = {2, 4, 6, 8}; Positioned valuesPositioned values – e.g. (Ada), – e.g. (Ada),
SCORE : SCORE : arrayarray (1..14, 1..2) := (1 => (24, 10), 2 => (10, 7), 3 (1..14, 1..2) := (1 => (24, 10), 2 => (10, 7), 3 =>(12, 30), =>(12, 30), othersothers => (0, 0)); => (0, 0));
Array OperationsArray Operations Assignment, Concatenation, Elemental ops. (+), etc.Assignment, Concatenation, Elemental ops. (+), etc. Intrinsic (library) operationsIntrinsic (library) operations (e.g., matrix ops) (e.g., matrix ops) APLAPL supports many array operations supports many array operations
Spring 2005 19
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Multi-dimensional ArraysMulti-dimensional Arrays
Rectangular ArrayRectangular Array Jagged ArrayJagged Array
Slices:Slices:Substructures of an arraySubstructures of an array
e.g., FORTRAN 90 INTEGER MAT (1:4, 1:4) MAT(1:4, 1) - the first column MAT(2, 1:4) - the second row
Spring 2005 20
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Implementation of Array TypesImplementation of Array Types
Access FunctionAccess Function: maps subscript expressions : maps subscript expressions to an address in the arrayto an address in the arrayaddr(A[k]) = addr(A[lbound]) + ((k - lbound) * ele_size);addr(A[k]) = addr(A[lbound]) + ((k - lbound) * ele_size);
Row major orderRow major order vs. vs. column major ordercolumn major order Compile-time descriptors:Compile-time descriptors:
Single-dimensioned
array
Multi-
dimensional array
Spring 2005 21
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Associative ArraysAssociative Arrays
Associative arrayAssociative array: an : an unordered collectionunordered collection of of data elements that are indexed by an equal data elements that are indexed by an equal number of values called number of values called keyskeys 1:1 correspondence between keys and values1:1 correspondence between keys and values Keys need to be stored in the array structureKeys need to be stored in the array structure e.g., Java’s e.g., Java’s MapMap interface, Perl’s interface, Perl’s hasheshashes
Design Issues:Design Issues:1. What is the1. What is the form of referencesform of references to elements? to elements?2. Is the size 2. Is the size static or dynamicstatic or dynamic??
KeyKeye.g., an email addresse.g., an email address
ValueValuee.g., a student namee.g., a student name
Associative Associative ArrayArray
Spring 2005 22
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Hashtable: An Implementation of Hashtable: An Implementation of an Associative Arrayan Associative Array
Hong, Kildong
KeysKeys ValuesValues
HashingHashingFunctionFunction
A BucketA Bucket
Spring 2005 23
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Record TypesRecord Types
RecordRecord: a possibly : a possibly heterogeneousheterogeneous aggregate aggregate of data elementsof data elements in which the individual in which the individual elements are identified by nameselements are identified by names
Design Issues:Design Issues:1. What is the 1. What is the form of referencesform of references? ?
2. What unit 2. What unit operationsoperations are defined? are defined?* AW Lecture Notes
Employee Employee == recordrecord
Name : Employ_Name;Name : Employ_Name;
Sex : (Female, Male);Sex : (Female, Male);
Hourly_Rate : Real;Hourly_Rate : Real;
endend;;
varvar Clerk : Employee; Clerk : Employee;
typetype
Employee_Name Employee_Name == recordrecord
First : String;First : String;
Middle : String;Middle : String;
Last : String;Last : String;
endend;;
Spring 2005 24
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Record Field ReferencesRecord Field ReferencesCOBOL; COBOL;
field_namefield_name OFOF record_name_1 record_name_1 OFOF ... ... OFOF record_name_n record_name_nOthers (Others (dot notationdot notation); );
record_name_1record_name_1..record_name_2record_name_2.. ... record_name_n ... record_name_n..field_namefield_name
Fully qualified referencesFully qualified references:: include all record names include all record namese.g., e.g., Clerk.Name.LastClerk.Name.Last
Elliptical referencesElliptical references:: allow leaving out record names as allow leaving out record names as long as the reference is unambiguouslong as the reference is unambiguous Pascal provides a Pascal provides a withwith clause to abbreviate references clause to abbreviate references
withwith ClerkClerk do dobeginbegin write(‘The wage of the clerk, ’);write(‘The wage of the clerk, ’); write(write(Name.FirstName.First); write(); write(Name.MiddleName.Middle); );
write(write(Name.LastName.Last);); write(‘ is $.’, write(‘ is $.’, Hourly_RateHourly_Rate :7:2); :7:2);endend
* AW Lecture Notes
Spring 2005 25
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Record OperationsRecord Operations
AssignmentAssignment e.g., e.g., Clerk := JanitorClerk := Janitor Pascal, Ada, and C allow it if the types are identicalPascal, Ada, and C allow it if the types are identical
InitializationInitialization e.g., e.g., Clerk = { { “Tom”, “J.”, “Lee” }, Male, 28.50 };Clerk = { { “Tom”, “J.”, “Lee” }, Male, 28.50 }; Allowed in Ada, using an aggregate constantAllowed in Ada, using an aggregate constant
ComparisonComparison e.g., e.g., if Clerk = Janitor then …if Clerk = Janitor then … In Ada, = and /=; one operand can be an aggregate constantIn Ada, = and /=; one operand can be an aggregate constant
MOVE CORRESPONDINGMOVE CORRESPONDING In COBOL - it moves all fields in the source record to fields with In COBOL - it moves all fields in the source record to fields with
the same names in the destination recordthe same names in the destination record See the example in the textbook (pp. 267)See the example in the textbook (pp. 267)
* AW Lecture Notes
Spring 2005 26
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
A Compile-time Descriptor for A Compile-time Descriptor for a Recorda Record
* AW Lecture Notes
Spring 2005 27
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Union (Variant Record) TypesUnion (Variant Record) Types
UnionUnion: a type whose variables are allowed to : a type whose variables are allowed to store different type values at different times store different type values at different times during executionduring execution
Design Issues for unions:Design Issues for unions:1. What kind of 1. What kind of type checkingtype checking, if any, must be done?, if any, must be done?
2. Should unions be 2. Should unions be integrated with recordsintegrated with records??
type type Node Node == recordrecord
casecase Tag : Boolean Tag : Boolean ofof
True : (Count : Integer);True : (Count : Integer);
False : (Sum : Real);False : (Sum : Real);
endend;;
var Uval : Node;var Uval : Node;
union union Node {Node {
int count;int count;
float sum;float sum;
} uval;} uval;
CC PascalPascal
Spring 2005 28
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Union (Variant Record) TypesUnion (Variant Record) Types
type type Node Node == recordrecord
casecase Tag : Boolean Tag : Boolean ofof
True : (Count : Integer);True : (Count : Integer);
False : (Sum : Real);False : (Sum : Real);
endend;;
var Uval : Node;var Uval : Node;
union union Node {Node {
int count;int count;
float sum;float sum;
} uval;} uval;
int utype;int utype;CC PascalPascal
Cont’dCont’d
Free UnionFree UnionNo language support for type No language support for type checkingchecking
Discriminated UnionDiscriminated UnionA union construct includes a A union construct includes a typetype indicatorindicator ( (tagtag or or discriminantdiscriminant))
uval:uval:
countcount
sumsum
uval:uval:
CountCount
SumSumtagtag
Allocate a big enough space to hold the “widest” memberAllocate a big enough space to hold the “widest” member
Spring 2005 29
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Union (Variant Record) TypesUnion (Variant Record) Types
type type Node Node == recordrecord
casecase Tag : Boolean Tag : Boolean ofof
True : (Count : Integer);True : (Count : Integer);
False : (Sum : Real);False : (Sum : Real);
endend;;
var Uval : Node;var Uval : Node;
union union Node {Node {
int count;int count;
float sum;float sum;
} uval;} uval;
int utype;int utype;CC PascalPascal
Cont’dCont’d
Free UnionFree Union Discriminated UnionDiscriminated Unionif (utype == INT)if (utype == INT)
printf(“%d”, uval.count);printf(“%d”, uval.count);
else if (utype == FLOAT)else if (utype == FLOAT)
printf(“%f”, uval.sum);printf(“%f”, uval.sum);
Uval.Tag := True;Uval.Tag := True;
Uval.Count := 1341;Uval.Count := 1341;
Uval.Tag := False;Uval.Tag := False;
var X := Uval.Sum; { ??? }var X := Uval.Sum; { ??? }
Unions are potentially unsafe constructsUnions are potentially unsafe constructs
In Ada, all assignments to the union must include the tag valueIn Ada, all assignments to the union must include the tag value
Spring 2005 30
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Pointer TypesPointer Types
Pointer TypePointer Type: a type in which the variables have a : a type in which the variables have a range of values that range of values that consists of memory addressesconsists of memory addresses and and a special value, a special value, nil (null)nil (null)
A pointer can be used to access a A pointer can be used to access a heap-dynamic heap-dynamic variablevariable
int n = 11;int n = 11;
int *p = 22;int *p = 22;
int *q, *r, *h;int *q, *r, *h;
q = &n; r = NULL;q = &n; r = NULL;
h = (int *)malloc(sizeof(int));h = (int *)malloc(sizeof(int));
*h = 33;*h = 33;
int m = *h;int m = *h;
11nn22
pp
NULL
qqrr
…
33
hh
Dereferencing Dereferencing (Indirect reference)(Indirect reference)
Spring 2005 31
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Pointer Problems –Pointer Problems –Dangling PointersDangling Pointers
int n = 11;int n = 11;
int *p = 22;int *p = 22;
int *q, *r, *h;int *q, *r, *h;
q = &n; r = NULL;q = &n; r = NULL;
h = (int *)malloc(sizeof(int));h = (int *)malloc(sizeof(int));
*h = 33;*h = 33;
r = h;r = h;
free(h);free(h);
11nn22
pp
NULL
qqrr
…
33
hh
A dangling pointerA dangling pointer
NULL
Spring 2005 32
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Pointer Problems –Pointer Problems –Lost Heap-dynamic VariablesLost Heap-dynamic Variables
int n = 11;int n = 11;
int *p = 22;int *p = 22;
int *q, *r, *h;int *q, *r, *h;
q = &n; r = NULL;q = &n; r = NULL;
h = (int *)malloc(sizeof(int));h = (int *)malloc(sizeof(int));
*h = 33;*h = 33;
h = NULL;h = NULL;
11nn22
pp
NULL
qqrr
…
33
hh NULL
A lost heap-dynamic variableA lost heap-dynamic variable
Garbage, Memory LeakageGarbage, Memory Leakage
Spring 2005 33
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Reference TypesReference Types
Reference Type VariableReference Type Variable: a constant pointer : a constant pointer that is always implicitly dereferenced (that is always implicitly dereferenced (aliasingaliasing))
C++ supports reference typesC++ supports reference types Improve readability in a function that uses Improve readability in a function that uses bi-bi-
directional variablesdirectional variables
int result = 100;int result = 100;
f(result);f(result);
void f(int *input) {void f(int *input) {
*input += 200;*input += 200;
}}
int result = 100;int result = 100;
f(result);f(result);
void f(int &input) {void f(int &input) {
input += 200;input += 200;
}}
Spring 2005 34
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Pointers in Java?Pointers in Java? No pointers, only No pointers, only
references to objectsreferences to objects (which are all on the (which are all on the heap)heap)
No explicit deallocator No explicit deallocator ((garbage collectiongarbage collection is is used)used)
There can be no There can be no dangling referencesdangling references
Dereferencing is Dereferencing is always implicitalways implicit
class DataClass {class DataClass {int number = 100;int number = 100;String name = “ICU”;String name = “ICU”;
}}class MainClass {class MainClass {
void aMethod(DataClass data) {void aMethod(DataClass data) { data.number += 200;data.number += 200; data.name = “Go ”+data.name;data.name = “Go ”+data.name;}}void mainMethod() {void mainMethod() { DataClass input=new DataClass();DataClass input=new DataClass(); aMethid(input);aMethid(input); System.out.println(input.name);System.out.println(input.name);
}}}}
* AW Lecture Notes
Spring 2005 35
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Reading Assignment #2Reading Assignment #2
Read Read Section 6.9.9Section 6.9.9 of the textbook of the textbook Solutions to the dangling pointer problemSolutions to the dangling pointer problem Heap managementHeap management
Garbage collectionGarbage collection