Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 6 Data Types Introduction:

Similar presentations


Presentation on theme: "Chapter 6 Data Types Introduction:"— Presentation transcript:

1 Chapter 6 Data Types Introduction:
This chapter first introduces the concept of data type and the characteristics of the common primitive data types. Then the design of enumeration and subrange types are discussed. Next ,structured data types ,specifically : Arrays ,records ,and unions.

2 Chapter 6 Data Types Introduction:
Set types are then discussed, followed by an in-depth look at pointers. The design issues are stated and design choices made by the designer(s) of the important languages are explained. Implementation methods for data types often have significant impact on their design.

3 Chapter 6 Data Types Data types roots is 50 years old.
FORTRAN I (1956) - INTEGER, REAL, arrays COBOL allow programmers to specify the accuracy of decimal data values. PL/I extends this to integer and floating points ALGOL provides few user-defined data types

4 User defined data types improve readability through the use of meaningful names for types.
User defined data types improve readability and modifiability. Ada (1983) - User can create a unique type for every category of variables in the problem space and have the system enforce the types Abstract data type was simulated in Ada83 Abstract data type is the use of a type separated from the representation and set of operations on values of that type.

5 Def: A descriptor is the collection of the attributes of a variable.
In an implementation, a descriptor is a collection of memory cells that store variable attributes.

6 Primitive Data Types Those not defined in terms of other data types
Numeric Character string User-defined ordinal Arrays Associative arrays Record Union Set Pointers

7 Numeric Types: Integer Floating Point Decimal Boolean Type
Character Type

8 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: integer, long integer, short integer, unsigned int, unsigned long int,... A negative integer could be stored in sign-magnitude notation, in which the sign bit is set to indicate negative and the remainder of the bit string represents the absolute value of the number.

9 Floating Point Model real numbers, but only as approximations (like pi). Languages for scientific use support at least two floating-point types; float and double, sometimes more Usually exactly like the hardware, but not always; some languages allow accuracy specs in code e.g. (Ada) type SPEED is digits 7 range ; type VOLTAGE is delta 0.1 range ;

10 IEEE floating point format for single and double precision
1 8 bits bits Sign bit Exponent Fraction Exponent Fraction bits bits IEEE floating point format for single and double precision

11 Decimal For business applications (money). Used in COBOL.
Store a fixed number of decimal digits (coded) using BCD system. Advantage: accuracy Disadvantages: limited range, wastes memory

12 Boolean: Boolean type are perhaps the simplest of the all types.
Their range of values has only two elements, one for true and one for false. Could be implemented as bits, but often as bytes C++ has Boolean type, but it allows expressions to be used as if they were expressions. Advantage: readability

13 Character type Are stored in computers as numeric coding. The most common one is ASCII. ASCII supports up to 128/256 characters. A new code called Unicode has been developed Unicode is 16-bit code. Java uses Unicode. Unicode includes the characters from most of the World’s natural languages. Example: Unicode includes the Cyrillic alphabet, as used in Serbia, and Thai digits.

14 Character String Types
A character string type is one in which values are sequences of characters Design issues: Is it a primitive type or just a special kind of array? Is the length of objects static or dynamic? Operations: Assignment Comparison (=, >, etc.) Catenation Substring reference for example Name1(2:4) Pattern matching

15 If strings are not defined as a primitive type, string data is usually stored in arrays of single characters and referenced as such in the language. This approach is done in C, C++, PASCAL, and ADA.

16 Examples: Pascal Ada, FORTRAN 77, FORTRAN 90 and BASIC e.g. (Ada)
Not primitive; assignment and comparison only (of packed arrays) Ada, FORTRAN 77, FORTRAN 90 and BASIC treats strings as a primitive type. Assignment, comparison, catenation, substring reference e.g. (Ada) N := N1 & N2 (catenation) N(2..4) (substring reference)

17 Examples C and C++ SNOBOL4 (a string manipulation language)
Not primitive Use char arrays and a library of functions that provide operations ( strcpy, strcat,…) SNOBOL4 (a string manipulation language) Primitive Many operations, including elaborate pattern matching e.g. (SNOBOL4) LETTER = ‘ABCDEFGHIGKLMNOPQRSTUVWXYZ’ ALI = BREAK(LETTER) SPAN ( LETTER).WORD TEXT WORD

18 Perl e.g., Java Patterns are defined in terms of regular expressions
A very powerful facility! e.g., /[A-Za-z][A-Za-z\d]+/ Java String class (not arrays of char)

19 String Length Options There are several design choices regarding the length of string variable: Static and specified in the declaration. FORTRAN 90, Ada, COBOL e.g. (FORTRAN 90) CHARACTER (LEN = 15) NAME1,nmae2; static variables are always full. If a shorter string is assigned to a string variable, the empty character are set to blank. Limited Dynamic Length :is to allow strings to have varying length up to a declared and fixed maximum set by the variable definition. Example: C and C++ such string variables can store any number of characters between Zero and the maximum.

20 String Length Options Dynamic
is to allow strings to have varying length with no maximum ,as SNOBOL4, Perl and javaScript. This option requires the overhead of dynamic storage allocation and deal location, but provides maximum flexibility.

21 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?

22 Implementation: Character string types are sometimes support directly in hardware, but in most cases software is used to implement string storage, retrieval, and Manipulation. When character string types are represented as Character arrays, the length often supplies few operations. A descriptor for a static character string type, Which is only required during compilation, has Three fields.

23 Compile time descriptor for static strings
Length Address ( Name) ( First character) Compile time descriptor for static strings

24 Limited dynamic length
Limited dynamic length - may need a run-time descriptor for length (but not in C and C++). In C and C++, the end of a string is marked with the null character. They do not need the maximum length because index values in array references are not range-checked in C and C++.

25 Run time descriptor for limited dynamic
Limited dynamic string Maximum Length Current Length Address Run time descriptor for limited dynamic strings

26 Dynamic length Dynamic length
Requires more complex storage management. The length of a string, and therefore the storage to which it is bound , must grow and shrink dynamically. There are two possible approaches to the dynamic allocation problem:

27 Linked list Solution to dynamic allocation problem
- Requires more storage - Allocation and deallocation process are simple Solution to dynamic allocation problem Adjacent storage cells - Faster - Requires less storage - The allocation process is slower

28 Ordinal Types (user defined)
An ordinal type is one in which the range of possible values can be easily associated with the set of positive integers Enumeration Types - one in which the user enumerates all of the possible values, which are symbolic constants example: type days is ( Mon, Tue, We, Thu, Fri, Sat, Sun) Design Issue: Should a symbolic constant be allowed to be in more than one type definition?

29 Examples: 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, blue, green, yellow} var ahmed : colortype; …… ahmed :=blue; if ahmed > red…

30 Examples: Ada - constants can be reused (overloaded literals); disambiguate with context or type_name ‘ (one of them); can be used as in Pascal; CAN be input and output type letter is ( ‘A’,’B’,’C’,’D’,……’z’) type vowel is (‘A’,’B’,C’,’D’,……’Z’); for letter in ‘A’..’N’ LOOP <-- ambiguous Now we remove the ambiguity for letter in vowel’(‘a’).. Vowels’(‘u’) loop

31 Examples: C and C++ - like Pascal, except they can be input
and output as integers Java does not include an enumeration type

32 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 operations and ranges of values

33 2. Subrange Type - an ordered contiguous
subsequence of an ordinal type Design Issue: How can they be used? Examples: Pascal - Subrange types behave as their parent types; can be used as for variables and array indices e.g. type pos = 0 .. MAXINT;

34 Ada - Subtypes are not new types, just constrained existing types (so they are compatible); can be used as in Pascal, plus case constants e.g. subtype POS_TYPE is INTEGER range 0 ..INTEGER'LAST;

35 Confusing point Type ahmed is new INTEGER range 1..100;
- inherit the value range and operations of integer, but are not compatible. subtype ALI is INTEGER range ; inherit the value range and operations of integer, and compatible.( subtype is not a new type ).

36 Evaluation of enumeration types:
- Aid to readability - Reliability - restricted ranges add error detection

37 - Enumeration types are implemented as
integers - Subrange types are the parent types with code inserted (by the compiler) to restrict assignments to subrange variables

38 Arrays An array is an aggregate of homogeneous data elements in which an individual element is identified by its position in the aggregate, relative to the first element.

39 Design Issues: 1. What types are legal for subscripts? 2. Are subscripting expressions in element references range checked? 3. When are subscript ranges bound? 4. When does allocation take place? 5. What is the maximum number of subscripts? 6. Can array objects be initialized? 7. Are any kind of slices allowed?

40 Indexing is a mapping from indices to
elements map(array_name, index_value_list)  an element Syntax - FORTRAN, PL/I, Ada use parentheses - Most others use brackets

41 In Fortran we can have: SUM = SUM + B(I) B(I) may be used to refer to array or to a subprogram call. This is frustrating to the reader In Ada, the compiler has access to information about previously compiled programs

42 Subscript Types: FORTRAN, C - int only Pascal - any ordinal type (int, boolean, char, enum) Ada - int or enum (includes boolean and char) Java - integer types only

43 Four Categories of Arrays (based on subscript
binding and binding to storage) 1. Static – is one in which the subscript ranges are statically bound and storage allocation is static( done before run time ). range of subscripts and storage bindings are static . e.g. FORTRAN 77, some arrays in Ada Advantage: execution efficiency (no allocation or deallocation) 2. Fixed stack dynamic – is one in which the subscript ranges are statically bound, but the allocation is done at declartion elaboration time.( during execution ) e.g. Pascal locals and, C locals that are not static Advantage: space efficiency

44 are dynamically bound and the storage allocation is
3. Stack-dynamic – is one in which the subscript ranges are dynamically bound and the storage allocation is dynamic.( done during run time ). 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

45 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) DEALLOCATE MAT (Deallocates MAT’s storage) - In APL & Perl, arrays grow and shrink as needed - In Java, all arrays are objects (heap-dynamic)

46 C and C++ provide dynamic arrays through
malloc and free in C and new and delete in C++

47 Number of subscripts - FORTRAN I allowed up to three
- FORTRAN 77 allows up to seven - C, C++, and Java allow just one, but elements can be arrays. - Others - no limit

48 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

49 Examples: 1. FORTRAN - uses the DATA statement, or put the values in / ... / on the declaration 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 SCORE : array (1..14, 1..2) := (1 => (24, 10), 2 => (10, 7), 3 =>(12, 30), others => (0, 0));

50 Array Initialization (continued)
4. Pascal and Modula-2 do not allow array initialization in the declaration Sections of programs.

51 Array Operations: is one that operates on an array as a unit
Array Operations: is one that operates on an array as a unit. Some languages such as FORTRAN 77 provide no array operations. 1. APL - many, see book (p ) 2. Ada - assignment; RHS can be an aggregate constant or an array name - catenation; for all single-dimensioned arrays - relational operators (= and /= only) 3. FORTRAN 90 - intrinsic (subprograms) for a wide variety of array operations (e.g., matrix multiplication, vector dot product).

52 Slices A slice is some substructure of an array; nothing
more than a referencing mechanism. It is important to realize that a slice is not a new data type. Rather is a mechanism for referencing part of an array as a unit

53 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)

54 Implementation of Arrays
- implementing arrays requires more compile-time effort than does implementing simple type ,such as integers The code to allow accessing of array elements must be generated at compile time . At run time ,this code must be executes to produce element addresses

55 Implementation of Arrays
- Access function maps subscript expressions to an address in the array - Row major (by rows) or column major order (by columns) - Fortran is column major order, while others are row major order.

56 Compile time descriptor for single-dimensional
Array element type index type index lower bound index upper bound address Compile time descriptor for single-dimensional array

57 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?

58 Associative arrays are in Perl and also supported
by the standard class library of Java.

59 Structure and operation
- In Perl associative arrays are called hashes. - In the implementation, their elements are stored and retrieved with hash functions. - The name space for Perl hashes is distict. - Every hash variable ( Name ) must begin with %

60 - Structure and Operations in Perl
- Names begin with % - Literals are delimited by parentheses e.g., %hi_temps = ("Monday" => 77, "Tuesday" => 79,…); - Subscripting is done using braces and keys $hi_temps{"Wednesday"} = 83; - Elements can be removed with delete delete $hi_temps{"Tuesday"};

61 Implementing associative arrays
Perl associative arrays are implemented by providing some fixed amount of space initially. When the structure reaches some predetermined level of fullness, it is expanded. This expansion process is costly, for it requires that a new hash function be used and all existing elements be rehashed into the structure.

62 Record Types 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?

63 Record Definition Syntax
- COBOL uses level numbers to show nested records; Example: 01 Employee-Record. 02 Employee-Name. 03 First picture is x(2). 03 Middle picture is x(10). 03 Last picture is x(20). 02 Hourly-Rte picture is 99v99.

64 In Object-Oriented, the class construct supports
records. C++ still includes C’s struct for record structure, although it is redundant. Java does not have struct.

65 Pascal, Modula-2, and Ada indicate record
structure in an orthogonal way by nesting records declarations inside record declaration. Ada Example Employee record: record Employee_name: First : string (1..20); Middle : string (1..20); Last : string( 1..20); end reocrd; Hourly_Rate : FLOAT; end record;

66 In Fortran 90 record declarations require that an nested records be previously defined as types

67 Record Field References
1. COBOL field_name OF record_name_1 OF ... OF record_name_n Example : Middle of Employee-Name of Employee-Record 2. Others (dot notation) record_name_1.record_name_2. ... .record_name_n.field_name

68 Fully qualified references must include all record
names Elliptical references allow leaving out record names as long as the reference is unambiguous COBOL and PL/I allow elliptical references. For example, First, and Last are elliptical references. Elliptical is : - Convenience to the programmer. - They require extra overhead by the compiler. - Somewhat detrimental to readability.

69 Pascal and Modula-2 provide a with clause to
abbreviate references Record Operations 1. Assignment - Pascal, Ada, and C allow it if the types are identical - In Ada, the RHS can be an aggregate constant

70 Record Operations (continued)
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

71 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) 2. Dynamic subscripts could be used with record field access, but it would disallow type checking and it would be much slower

72 Unions A union is a type whose variables are allowed to
store different type values at different times during execution

73 Design Issues for unions:
1. What kind of type checking, if any, must be done? 2. Should unions be integrated with records?

74 Examples: 1. FORTRAN - with EQUIVALENCE 2. Algol discriminated unions - Use a hidden tag to maintain the current type - Tag is implicitly set by assignment - References are legal only in conformity clauses (see book example p. 231) - This runtime type selection is a safe method of accessing union objects

75 3. Pascal - both discriminated and
nondiscriminated unions e.g. type intreal = record tagg : Boolean of true : (blint : integer); false : (blreal : real); end;

76 Problem with Pascal’s design: type checking is
ineffective Reasons: a. User can create inconsistent unions (because the tag can be individually assigned) var blurb : intreal; x : real; blurb.tagg := true; { it is an integer } blurb.blint := 47; { ok } blurb.tagg := false; { it is a real } x := blurb.blreal; { assigns an integer to a real }

77 b. The tag is optional! - Now, only the declaration and the second and last assignments are required to cause trouble

78 4. Ada - discriminated unions
- Reasons they are safer than Pascal & Modula-2: 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)

79 5. C and C++ - free unions (no tags)
- Not part of their records - No type checking of references 6. Java has neither records nor unions Evaluation - potentially unsafe in most languages (not Ada)

80 Sets A set is a type whose variables can store unordered
collections of distinct values from some ordinal type Called its base type. Design Issue: What is the maximum number of elements in any set base type? Examples: 1. Pascal - No maximum size in the language definition (not portable, poor writability if max is too small) - Operations: union (+), intersection (*), difference (-), =, <>, superset (>=), subset (<=), in

81 - Additional operations: INCL, EXCL, /
Examples (continued) 2. Modula-2 and Modula-3 - Additional operations: INCL, EXCL, / (symmetric set difference (elements in one but not both operands)) 3. Ada - does not include sets, but defines in as set membership operator for all enumeration types 4. Java includes a class for set operations

82 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 operations Implementation - Usually stored as bit strings and use logical operations for the set operations

83 Pointer Types A pointer type is a type in which the variables have a range of values that consists of memory addresses and a special value, nil (or null). The value nil is not a valid address and is used to indicate that a pointer cannot currently be used to reference any memory cell. Uses: 1. Addressing flexibility: indirect addressing 2. Dynamic storage management

84 A pointer can be used to access a location in the
area where storage is dynamically allocated, which is usually called a heap. Variables that are dynamically allocated from the heap are called heap-dynamic variables. They often do not have identifiers associated with them and thus can be referenced only by pointer or reference type variables. Variables without names are called anonymous variables. Pointers, unlike arrays and records, are not structured types, although they are defined using a type operator *

85 Pointers adds writability to a language. For
example, it is difficult to implement a binary tree in Fortran 77 since there is no pointers

86 Design Issues: 1. What is the scope and lifetime of pointer variables?
2. What is the lifetime of heap-dynamic 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?

87 Fundamental Pointer Operations:
1. Assignment of an address to a pointer 2. References (explicit versus implicit dereferencing)

88 77 k 77

89 In Fortran 90 and Algol 68 the
dereferencing is implicit.

90 Pointers Problems - The first high-level programming language
that include pointer variable was PL/I. They are very flexible, but can lead to many errors. - Java replaced pointers completely with reference types, which, along with implicit deallocation, eliminate the primary problems with pointers.

91 Problems with pointers:
1. Dangling pointers (dangerous) - A pointer points to a heap-dynamic variable that has been deallocated - Creating one: 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

92 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 - The process of losing heap-dynamic variables is called memory leakage

93 Examples: 1. Pascal: used for dynamic storage management only
- Explicit dereferencing - Dangling pointers are possible (dispose) - Dangling objects are also possible

94 2. Ada: a little better than Pascal and Modula-2
- Some dangling pointers are disallowed because dynamic objects can be automatically deallocated at the end of pointer's scope - All pointers are initialized to null - Similar dangling object problem (but rarely happens)

95 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] - void * - can point to any type and can be type checked (cannot be dereferenced)

96 4. FORTRAN 90 Pointers - Can point to heap and non-heap variables - Implicit dereferencing - Special assignment operator for non- dereferenced references

97 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)) - The TARGET attribute is assigned in the declaration, as in: INTEGER, TARGET :: NODE

98 5. C++ Reference Types - Constant pointers that are implicitly dereferenced - Used for parameters - Advantages of both pass-by-reference and pass-by-value 6. Java - Only references - No pointer arithmetic - Can only point at objects (which are all on the heap) - No explicit deallocator (garbage collection is used) - Means there can be no dangling references - Dereferencing is always implicit

99 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 3. Pointers are necessary--so we can't design a language without them

100 Solutions to the Dangling pointer problem
1- tombstones: Uses extra heap cells called tombstones 2- locks and keys approach.

101 Heap Dynamic variable With Tombstones

102 Tombstone Dynamic variables Heap Without tombstone


Download ppt "Chapter 6 Data Types Introduction:"

Similar presentations


Ads by Google