6.1 Introduction 6.2 Primitive Data Types - Evolution of Data Types:

Slides:



Advertisements
Similar presentations
Names and Bindings.
Advertisements

Various languages….  Could affect performance  Could affect reliability  Could affect language choice.
Chapter 6 Structured Data Types Arrays Records. Copyright © 2007 Addison-Wesley. All rights reserved. 1–2 Definitions data type –collection of data objects.
ISBN Lecture 06 Data Types. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.6-2 Lecture 06 Topics Introduction Primitive Data.
ISBN Chapter 6 Data Types: Structured types.
ISBN Chapter 6 Data Types. Copyright © 2006 Addison-Wesley. All rights reserved.1-2 Definitions A data type defines a collection of data.
ISBN 0-321— Chapter 6 Data Types. Copyright © 2007 Addison-Wesley. All rights reserved.1-2 Chapter 6 Topics Introduction Primitive Data Types Character.
Chapter 6 Structured Data Types Arrays Records. Copyright © 2007 Addison-Wesley. All rights reserved. 1–2 Definitions data type –collection of data objects.
ISBN 0-321— Chapter 6 Data Types. Copyright © 2007 Addison-Wesley. All rights reserved.1-2 Chapter 6 Topics Introduction Primitive Data Types Character.
College of Computer Science and Engineering
ISBN 0-321— Chapter 6 Data Types. Corrected and improved by Assoc. Prof. Zeki Bayram, EMU, North Cyprus. Original Copyright © 2007 Addison-Wesley.
ISBN 0-321— Chapter 6 sections 1-4, 9 Primitive Data Types Numbers Strings Ordinal Types Pointers.
1 Data Types In Text: Chapter 5. 2 Chapter 5: Data Types Outline What is a type? Primitives Strings Ordinals Arrays Records Sets Pointers.
6-1 Chapter 6: Data Types Introduction Primitive Data Types Character String Types User-Defined Ordinal Types Array Types Associative Arrays Record Types.
ISBN 0-321— Chapter 6 Structured Data Types Arrays Associated Arrays Records Unions.
1 Records Record aggregate of data elements –Possibly heterogeneous –Elements/slots are identified by names –Elements in same fixed order in all records.
ISBN Chapter 6 Data Types Introduction Primitive Data Types User-Defined Ordinal Types.
ISBN Chapter 6 Data Types. Copyright © 2006 Addison-Wesley. All rights reserved.1-2 Chapter 6 Topics Introduction Primitive Data Types Character.
ISBN Chapter 6 Data Types. Copyright © 2006 Addison-Wesley. All rights reserved.1-2 Chapter 6 Topics Introduction Primitive Data Types Character.
ISBN Chapter 6 Data Types. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.6-2 Chapter 6 Topics Introduction Primitive Data.
ISBN 0-321— Chapter 6 Data Types. Copyright © 2007 Addison-Wesley. All rights reserved.1-2 Chapter 6 Topics Introduction Primitive Data Types Character.
C H A P T E R S I X Data Types.
CS 363 Comparative Programming Languages Data Types.
1 CS Programming Languages Class 09 September 21, 2000.
ISBN Chapter 6 Data Types Pointer Types Reference Types Memory Management.
1 CS Programming Languages Class 08 September 19, 2000.
ISBN Chapter 6 Structured Data Types Array Types Associative Arrays Record Types Union Types.
ISBN Chapter 6 Data Types. Copyright © 2006 Addison-Wesley. All rights reserved. 6-2 Chapter 6 Topics Introduction Primitive Data Types.
1 Data Types Primitive Data Types Character String Types User-Defined Ordinal Types Array Types Associative Arrays Record Types Union Types Pointer Types.
Data Types W E E K F O U R. Copyright © 2006 Addison-Wesley. All rights reserved.1-2 Chapter 6 Topics Introduction Primitive Data Types Character String.
How to execute Program structure Variables name, keywords, binding, scope, lifetime Data types – type system – primitives, strings, arrays, hashes – pointers/references.
Chapter 6 © 2002 by Addison Wesley Longman, Inc Introduction - Evolution of Data Types: FORTRAN I (1957) - INTEGER, REAL, arrays … Ada (1983) -
ISBN Chapter 6 Data Types. Copyright © 2006 Addison-Wesley. All rights reserved.1-2 Chapter 6 Topics Introduction Primitive Data Types Character.
ISBN Chapter 6 Data Types. Copyright © 2006 Addison-Wesley. All rights reserved.2 Primitive Data Types Almost all programming languages.
Copyright © 1998 by Addison Wesley Longman, Inc. 1 Chapter 5 Evolution of Data Types: FORTRAN I (1956) - INTEGER, REAL, arrays … Ada (1983) - User can.
Chapter 6 Chapter 6 Data Types. Data Types  A data type defines  a collection of data objects, and  a set of predefined operations on the objects type:
Structure of Programming Language Data Types. 2 A data type defines a collection of data objects and a set of predefined operations on those objects An.
Data Types Chapter 6: Data Types Lectures # 12. Topics Chapter 6: Data Types 2 Introduction Primitive Data Types Character String Types Array Types Associative.
Data Types Chapter 6: Data Types Lectures # 13. Topics Chapter 6: Data Types 2 Introduction Primitive Data Types Character String Types Array Types Associative.
Data Types Chapter 6: Data Types Lectures # 11. Topics Introduction Primitive Data Types Character String Types Array Types Associative Arrays Record.
5.2 Names - We discuss all user-defined names here
5.2 Names - We discuss all user-defined names here
Object Lifetime and Pointers
Data Types In Text: Chapter 6.
Dr. Vamsi Paruchuri University of Central Arkansas
Chapter 6 Data Types.
Data Types I Subject : T0152 – Programming Language Concept
Chapter 6 Data Types.
Chapter 6 – Data Types CSCE 343.
CMP 339/692 Programming Languages Day 14 Tuesday, March 20, 2012
Chapter 6 Data Types.
Type Checking Generalizes the concept of operands and operators to include subprograms and assignments Type checking is the activity of ensuring that the.
6.1 Introduction 6.2 Primitive Data Types - Evolution of Data Types:
Type Checking, and Scopes
Chapter 6: Data Types Lectures # 10.
Structure of Programming Language
CSE 452: Programming Languages
Records Design Issues: 1. What is the form of references?
Concepts of programming languages
Chapter 6 Data Types.
Data Types In Text: Chapter 6.
Complex Data Types One very important measure of the “goodness” of a PL is the capability of its data types to model the problem space variables Design.
Chapter 6 Data Types.
Chapter 6 Data Types.
Chapter 6 Data Types.
Chapter 6 Data Types.
Chapter 6 Data Types.
Chapter 6 Data Types.
Chapter 6 Data Types Introduction:
Chapter 6 Data Types.
Presentation transcript:

6.1 Introduction 6.2 Primitive Data Types - Evolution of Data Types: FORTRAN I (1957) - INTEGER, REAL, arrays … Ada (1983) - User can create a unique type for every category of variables in the problem space and have the system enforce the types - Def: A descriptor is the collection of the attributes of a variable (collection of memory cells that store these values) - Design Issues for all data types: 1. What is the syntax of references to variables? 2. What operations are defined and how are they specified? 6.2 Primitive Data Types - Those not defined in terms of other data types 1. Integer - Almost always an exact reflection of the hardware, so the mapping is trivial - There may be as many as eight different integer types in a language (short, long, unsigned etc)

6.2 Primitive Data Types 2. Floating Point - Model real numbers, but only as approximations - Languages for scientific use support at least two floating-point types ex. Float (4 bytes) and Double(8 bytes) - Usually exactly like the hardware, but not always; some languages allow accuracy specs in code e.g. (Ada) type VOLTAGE is delta 0.1 range -12.0..24.0; 3. Decimal - For business applications (money) - Store a fixed number of decimal digits (coded) - Advantage: accuracy - Disadvantages: limited range – no exponent waists memory – could be one digit per digit 4. Boolean introduced in ALGOL 60 - Could be implemented as bits, but often as bytes - Advantage: readability

Figure 6.1 IEEE floating-point formats: (a) Single precision, (b) Double precision

6.3 Character String Types - Values are sequences of characters Design issues: 1. Is it a primitive type or just a special kind of array? 2. Is the length of objects static or dynamic? Operations: - Assignment - Comparison (=, >, etc.) - Catenation name1 := name1 & name2 (ADA) - Substring reference name(2:4) - Pattern matching Examples: - Pascal - Not primitive; assignment and comparison only (of packed arrays) - Ada, FORTRAN 90, and BASIC - Somewhat primitive - Assignment, comparison, catenation, substring reference - FORTRAN has an intrinsic for pattern matching

6.3 Character String Types (continued) - C and C++ - Not primitive - Use char arrays and a library of functions that provide operations - SNOBOL4 (a string manipulation language) - Primitive - Many operations, including elaborate pattern matching letter = ‘abc……z’ wordpat = BREAK(letter) SPAN(letter) . word skip until letter, collect all letters, put to “are ” - Perl and JavaScript - Patterns are defined in terms of regular expressions - A very powerful facility! - e.g., /[A-Za-z][A-Za-z\d]+/ One letter followed by any number of letters and digits - Java - String class (not arrays of char), the values are constant strings - StringBuffer a class for changeable strings, subscription is allowed

6.3 Character String Types (continued) - String Length Options: 1. Static - FORTRAN 77, Ada, COBOL e.g. (FORTRAN 90) CHARACTER (LEN = 15) NAME; 2. Limited Dynamic Length – Allow up to max. string size. C and C++ actual length is indicated by a null character 3. Dynamic - SNOBOL4, Perl, JavaScript Size can be determined during execution - Evaluation (of character string types): - Aid to writability - As a primitive type with static length, they are inexpensive to provide--why not have them? - Dynamic length is nice, but is it worth the expense? (overhead of alloc. And DeAlloc) - Implementation: - Static length - compile-time descriptor - Limited dynamic length - may need a run-time descriptor for length (but not in C and C++) - Dynamic length - need run-time descriptor; allocation/deallocation is the biggest implementation problem

Figure 6.2 Compile-time descriptor for static strings

Figure 6.3 Run-time descriptor for limited dynamic strings

6.4 User-Defined Ordinal Types - An ordinal type is one in which the range of possible values can be easily associated with the set of positive integers, ex. Integer, char and boolean Also, user can define: Enumeration & Subrange 1. Enumeration Types - one in which the user enumerates all of the possible values, which are symbolic constants ex. Type DAYS is (mon, tue, wed, thu,fri,sat,sun); mon, tue etc are symbolic constants Design Issue: Should a symbolic constant be allowed to be in more than one type definition? Ex. Pascal - cannot reuse constants; they can be used for array subscripts, for variables, case selectors; NO input or output; can be compared type colortype = (red, green, blue); var color : colortype; …… color := blue; if color > red then (*returns true *)

6.4 User-Defined Ordinal Types (continued) C and C++ - like Pascal, except they can be input and output as integers Ada - can be used as in Pascal; CAN be input and output. Also, constants can be reused (overloaded literals); disambiguate with context or type_name ‘ (one of them); ex. Type digit is (‘1’, ‘2’, ‘3’, ‘4’, ‘5’); type odd is (‘1’, ‘3’, ‘5’); - for num in ‘1’..’5’ loop … (which? use the type explicitly - for num in odd’ (‘1’).. odd’ (‘5’) loop - Evaluation (of enumeration types): a. Aid to readability--e.g. no need to code a color as a number b. Aid to reliability--e.g. compiler can check: i. operations (don’t allow colors to be added) ii. ranges of values (if you allow 7 colors and code them as the integers, 1..7, 9 will be a legal integer (and thus a legal color))

2. Subrange Type - An ordered contiguous subsequence of an ordinal type - Design Issue: How can they be used? - Examples: Pascal ex. type uppercase = ‘A’..’Z’; index = 1..100 - Subrange types behave as their parent types; can be used as for variables and array indices e.g. type pos = 0 .. MAXINT;

6.4 User-Defined Ordinal Types (continued) - Examples of Subrange Types (continued) Ada - Subtypes are not new types, just constrained existing types (so they are compatible); can be used as in Pascal, plus case constants ex. subtype index is INTEGER range 0 .. 100; inherits the operations of the parent type ex. day1 : days; day2 : weekdays; (subtype of days) . . . day2 = day1. . . (allowed expect day1 is sat or sun) - Evaluation of subrange types: - Aid to readability - Reliability - restricted ranges add error detection - Implementation of user-defined ordinal types - Enumeration types are implemented as integers - Subrange types are the parent types with code inserted (by the compiler) for the range check

6.5 Arrays - An array is an aggregate of homogeneous data elements in which an individual element is identified by its position relative to the first element. - Design Issues: 1. What types are legal for subscripts? (integer or all ordinal?) 2. Are subscripting expressions in element references range checked? (out of range?) 3. When are subscript ranges bound? (sometimes dynamic) 4. When does allocation take place? (static, dynamic etc) 5. What is the maximum number of subscripts? (dimension) 6. Can array objects be initialized? 7. What operations allowed 8. Are any kind of slices allowed? - Indexing is a finite mapping from indices to elements array_name(index_value)  an element - Index Syntax - FORTRAN, PL/I, Ada use parentheses sum = sum + B(I); function call or array? - Most other languages use brackets

6.5 Arrays (continued) - Subscript Types: FORTRAN, C - integer only Pascal - any ordinal type (integer, boolean, char, enum) Ada - integer or enum (includes boolean and char) Java - integer types only - Four Categories of Arrays (based on subscript binding and binding to storage) 1. Static - range of subscripts and storage bindings are static (before run-time) e.g. FORTRAN 77, some arrays in Ada Advantage: execution efficiency (no allocation or deallocation) 2. Fixed stack dynamic – range of subscripts is statically bound, but storage is bound at elaboration time e.g. Most Java locals, and C locals that are not static Advantage: space efficiency

3. Stack-dynamic - range and storage are dynamic, 6.5 Arrays (continued) 3. Stack-dynamic - range and storage are dynamic, but fixed from then on for the variable’s lifetime e.g. Ada declare blocks get (N); declare STUFF : array (1..N) of FLOAT; begin ... end; Advantage: flexibility - size need not be known until the array is about to be used 4. Heap-dynamic - subscript range and storage bindings are dynamic and not fixed e.g. (FORTRAN 90) INTEGER, ALLOCATABLE, ARRAY (:,:) :: MAT (Declares MAT to be a dynamic 2-dim array) ALLOCATE (MAT (10, NUMBER_OF_COLS)) (Allocates MAT to have 10 rows and NUMBER_OF_COLS columns, lowerbound=1) DEALLOCATE MAT (Deallocates MAT’s storage) - In APL, Perl, and JavaScript, arrays grow and shrink as needed - In Java, all arrays are objects (heap-dynamic)

6.5 Arrays (continued) - Number of subscripts (Dimension) - FORTRAN I allowed up to three - FORTRAN 77 allows up to seven - Others - no limit Array Initialization - Usually just a list of values that are put in the array in the order in which the array elements are stored in memory Examples: 1. FORTRAN - uses the DATA statement, or put the values in / ... / on the declaration ex. Integer list(3) data list /0,5,5/ 2. C and C++ - put the values in braces; can let the compiler count them e.g. int stuff [] = {2, 4, 6, 8}; 3. Ada - positions for the values can be specified e.g. SCORE : array (1..14, 1..2) := (1 => (24, 10), 2 => (10, 7), 3 =>(12, 30), others => (0, 0)); 4. Pascal does not allow array initialization

6.5 Arrays (continued) - Array Operations 1. Ada - Assignment; RHS can be an aggregate constant or an array name - Catenation; for all single-dimensioned arrays - Relational operators (= and /= only) 2. FORTRAN 90 - elemental operations, (such as arithmetic ops, assign, rel. ops) ex. + means the sum of two arrays, - subprograms for a wide variety of array operations (e.g., matrix multiplication, vector dot product) 3. APL – many ex. - A+B (A, B can be array, matrix) A x B (inner product) - collection of unary operators such as ΘM reverses the rows of M

- A slice is some substructure of an array; nothing 6.5 Arrays (continued) - Slices - A slice is some substructure of an array; nothing more than a referencing mechanism - Slices are only useful in languages that have array operations - Slice Examples: 1. FORTRAN 90 INTEGER MAT (1 : 4, 1 : 4) MAT(1 : 4, 1) - the first column MAT(2, 1 : 4) - the second row 2. Ada - single-dimensioned arrays only LIST(4..10)

Figure 6.4 Example slices in FORTRAN 90

Implementation of Arrays - one dimensional array access function maps subscript expressions to an address in the array address(list[k]) = address(list[1]) + (k-1)*element_size; or = address(list[1] – element_size) + k * element_size; (where the first elements is fixed) Cost: one subtraction and one mult vs. one multiplication

Figure 6.5 Compile-time descriptor for single-dimensioned arrays

Multi- dimensional array Row major (by rows) or column major order (by columns ) Ex. 3 4 7 1 2 5 - row major: 3 4 7 1 2 5 - Col. Major: 3 1 4 2 5 7 5 (Fortran) - access function for a [m,n] with row major: address(a[i, j]) = address (a[1,1]) + ((( (i-1)*n) + (j-1))*elem.size) or = address(a[1,1]) – ((n+1)*elem.size) + ((I*n+j)*elem.size) - first two terms are constant

Figure 6.6 The location of the [i, j] element in a matrix

- Elements can be removed with delete delete $hi_temps{"Tuesday"}; 6.6 Associative Arrays - An associative array is an unordered collection of data elements that are indexed by an equal number of values called keys - Design Issues: 1. What is the form of references to elements? 2. Is the size static or dynamic? Structure and Operations in Perl called “hashes” since hash function is used to store and retrieve elements - Names begin with % - Literals are delimited by parentheses e.g., %hi_temps = ("Monday" => 77, "Tuesday" => 79,…); - Subscripting is done using braces and keys e.g., $hi_temps{"Wednesday"} = 83; - Elements can be removed with delete delete $hi_temps{"Tuesday"};

6.7 Records - A record is a possibly heterogeneous aggregate of data elements in which the individual elements are identified by names - Design Issues: 1. What is the form of references? 2. What unit operations are defined? - Record Definition Syntax - COBOL uses level numbers to show nested records; others use recursive definitions ex. Cobol: 01 employee-record. 02 employee-name. 05 first picture is x(20). 05 last picture is x(20). 02 rate picture is 99v99 Ada: employee_record record employee_name: first : string (1..20); last : string (1..20); end record; rate : float; -

Record Field References 1. COBOL field_name OF record_name_1 OF ... OF record_name ex first of employ-name of employee-record 2. Others (dot notation) record_name_1.record_name_2. ... .record_name_n.field_name ex. employee_record.employee_name.first - Fully qualified references must include all record names - Elliptical references allow leaving out record names as long as unambiguous ex. first of employee-name or first of employee-record - Pascal provides a with clause to abbreviate references ex. With employee do ….(* refer indiv. field *)

6.7 Records (continued) - Record Operations 1. Assignment - Pascal, Ada, and C allow it if the types are identical - In Ada, the RHS can be an aggregate constant 2. Initialization - Allowed in Ada, using an aggregate constant 3. Comparison - In Ada, = and /=; one operand can be an aggregate constant 4. MOVE CORRESPONDING - In COBOL - it moves all fields in the source record to fields with the same names in the destination record ex. move corresponding record abc to xyz. - Comparing records and arrays 1. Access to array elements is much slower than access to record fields, because subscripts are dynamic (field names are static – each field can be accessed not in any order) 2. Dynamic subscripts could be used with record field access, but it would disallow type checking and it would be much slower

Figure 6.8 A compile-time descriptor for a record

6.8 Unions - A union is a type whose variables are allowed to store different type values at different times during execution - Design Issues for unions: 1. What kind of type checking, if any, must be done? 2. Should unions be embedded in records? - Examples: 1. FORTRAN - with EQUIVALENCE - No type checking (called free union) 2. Pascal - both discriminated (use of a tag) and nondiscriminated unions e.g. type intreal = record tagg : Boolean of true : (blint : integer); false : (blreal : real); end; - Problem with Pascal’s design: type checking is ineffective

6.8 Unions (continued) Reasons why Pascal’s unions cannot be type checked effectively: a. User can create inconsistent unions (because the tag can be individually assigned) ex. type intreal = record tagg : Boolean of true : (blint : integer); false : (blreal : real); end; var wow : intreal; x : real; wow.tagg := true; { it is an integer } wow.blint := 47; { ok } wow.tagg := false; { it is a real } {the value blreal is not assigned yet} x := wow.blreal; { assigns an integer to a real } b. The tag is optional! - Now, only the declaration and the second and last assignments are required to cause trouble wow.blint := 47; x := wow.blreal;

3. Ada - discriminated unions - Reasons they are safer than Pascal: a. Tag must be present b. It is impossible for the user to create an inconsistent union (because tag cannot be assigned by itself--All assignments to the union must include the tag value, because they are aggregate values) ex. wow := (tagg =>true, blint => 47); wow := (tagg => false, blreal =>31.4); 4. C and C++ - free unions (no tags) - Not part of their records - No type checking of references 5. Java has neither records nor unions Evaluation - potentially unsafe in most languages (not Ada)

Implementation of union; Discriminated Unions: use same address for all possible variants. Ex. type shape = (circle, triangle, rectangle); colors = (red, green, blue); figure = record filled : boolean; color: colors; case form: shape of circle: (diameter : real); triangle: ( leftside, rightside: integer; angle: real); rectangle: (side1, side2: integer); end;

Figure 6.9 A discriminated union of three shape variables (assume all variables are the same size)

6.9 Sets - A set is a type whose variables can store unordered collections of distinct values from some ordinal type - Design Issue: What is the maximum number of elements in any set base type? - Example - Pascal - No maximum size in the language definition (not portable, poor writability if max is too small) - Operations: in, union (+), intersection (*), difference (-), =, <>, superset (>=), subset (<=) Ex. Type colors = (red, blue, green, white); colorset = set of colors; var set1, set2, set3 : colorset; set1 := [red, green]; set2 := [green, white]; set3 := set1 + set2; set3 := set1 * set2; etc

- Examples (continued) 2. Ada - does not include set type 6.9 Sets - Examples (continued) 2. Ada - does not include set type but set membership operator for all enumeration types is provided using in 3. Java includes a class for set operations Evaluation - If a language does not have sets, they must be simulated, either with enumerated types or with arrays - Arrays are more flexible than sets, but have much slower set operations Implementation operations for the set operations ex. If the set type is [‘a’,’b’,’c’,’d’] the a variable needs 4 digits, one per member e.g., if the variable has only ‘a’ then 1000

6.10 Pointers - A pointer type is a type in which the range of values consists of memory addresses and a special value, nil (or null) - Uses: 1. Addressing flexibility 2. Dynamic storage management - Design Issues: 1. What is the scope and lifetime of pointer variables? 2. What is the lifetime of heap-dynamic variables? 3. Are pointers restricted to pointing at a particular type? 4. Are pointers used for dynamic storage management, indirect addressing, or both? 5. Should a language support pointer types, reference types, or both? - Fundamental Pointer Operations: 1. Assignment of an address to a pointer 2. Dereferencing (explicit versus implicit) most PL: explicit (ue of * operator in c, c++) ex. J = *ptr;

Figure 6.11 The assignment operation j = *ptr

6.10 Pointers - Problems with pointers: 1. Dangling pointers (dangerous) - A pointer points to a heap-dynamic variable that has been deallocated - Creating one (with explicit deallocation): a. Allocate a heap-dynamic variable and set a pointer to point at it b. Set a second pointer to the value of the first pointer c. Deallocate the heap-dynamic variable, using the first pointer 2. Lost Heap-Dynamic Variables ( wasteful) - A heap-dynamic variable that is no longer referenced by any program pointer - Creating one: a. Pointer p1 is set to point to a newly created heap-dynamic variable b. p1 is later set to point to another newly created heap-dynamic variable - The process of losing heap-dynamic variables is called memory leakage

6.10 Pointers (continued) - Examples: 1. Pascal: used for dynamic storage management only - Explicit dereferencing (postfix ^) - Dangling pointers are possible (dispose) - Dangling objects (heap-variables) are also possible 2. Ada: a little better than Pascal - Some dangling pointers are disallowed because dynamic objects can be automatically deallocated at the end of pointer's type scope - All pointers are initialized to null - Similar dangling object problem (but rarely happens, because explicit deallocation is rarely done)

6.10 Pointers (continued) 3. C and C++ - Used for dynamic storage management and addressing - Explicit dereferencing and address-of operator - Can do address arithmetic in restricted forms - Domain type need not be fixed (void * ) e.g. float stuff[100]; float *p; p = stuff; *(p+5) is equivalent to stuff[5] and p[5] *(p+i) is equivalent to stuff[i] and p[i] (Implicit scaling) - void * - Can point to any type and can be type checked (cannot be dereferenced)

6.10 Pointers (continued) 4. FORTRAN 90 Pointers - Can point to heap and non-heap variables - Implicit dereferencing INTEGRER, POINTER :: ptr; …. N0 = ptr;….. - Pointers can only point to variables that have the TARGET attribute - The TARGET attribute is assigned in the declaration, as in: INTEGER, TARGET :: NODE ( now node can be pointed by ptr) - A special assignment operator is used for non-dereferenced references e.g. REAL, POINTER :: ptr (POINTER is an attribute) ptr => target (where target is either a pointer or a non-pointer with the TARGET attribute)) - This sets ptr to have the same value as target (to have address value)

6.10 Pointers (continued) 5. C++ Reference Types - Constant pointers that are implicitly dereferenced ex. Int result = 0; int &t_result = result; (set the address of int_result, cannot be changed) t_result = 100; (implicit referencing) - Used for parameters Advantages of both pass-by-reference and pass-by-value 6. Java - Only references - Can only point at objects – class instances - No pointer arithmetic - No explicit deallocator (garbage collection is used) - Means there can be no dangling references - Dereferencing is always implicit

Evaluation of pointers: 1. Dangling pointers and dangling objects are problems, as is heap management 2. Pointers are like goto's--they widen the range of cells that can be accessed by a variable. The most damning statement (Hoare): “their introduction to HLL has been a step backward from which we may never recover” 3. Pointers or references are necessary for dynamic data structures--so we can't design a language without them

6.10 Implementation of Pointers - Single value stored in memory, Usually 4 bytes Ex. All 4 bytes for address or 2 for segment and 2 for off-set solution to dangling pointer “tombstone”: the idea is that all heap-dynamic variables to have a extra cell called “tombstone” it points to the heap-dynamic variable. if deallocated => it points to nil. I.e., if the pointer variable points to tombstone which is nil, then there is an error. useful but costly: - Tombstone : never deallocated - one more indirection

Figure 6.12 Implementing dynamic variables with and without tombstones

Reclaiming the Garbage: Garbage occurs to the explicit deallocation Of the memory (ex. Delete – memory without references) Use of reference counter – reclaim in incremental and done whenever inaccessible memory is created. - Each cell has a counter which counts the number of pointers the pointers if counter = 0, then collect it. problems: - counting is expensive - circular list (each counter has at least 1 !) Garbage collection: one if no available memory. - need to set the tags of used cells I.e., trace all program variables. if a cell is connected , set it to 1 (marking algorithm) - collect that are unmarked

Figure 6.13 An example of the actions of the marking algorithm For every pointer r do mark( r); Procedure mark(ptr); if ptr <> nil then if ptr^.tag not marked set ptr^.tag mark (ptr^.left); mark(ptr^.right); endif