840 likes | 1.18k Views
Chapter 6 Data Types. Fall 2014. Introduction. A data type: = a collection of data objects + a set of predefined operations The design issues How to represent data objects? What operations are defined and how are they specified?
E N D
Chapter 6 Data Types Fall 2014 CS 1621
Introduction • A data type: = a collection of data objects + a set of predefined operations • The design issues • How to represent data objects? • What operations are defined and how are they specified? • A descriptor is the collection of the attributes of an object PITT CS 1621
Primitive Data Types • Primitive data types • Those not defined in terms of other data types • Almost all programming languages provide a set of primitive data types • Some primitive data types are merely reflections of the hardware; others require little non-hardware support PITT CS 1621
Primitive Data Types: Integer • Almost always an exact reflection of the hardware so the mapping is trivial Example: Java’s signed integer sizes: byte, short, int, long • Storing negative integer values • 1’s complement -100 = ? • 2’s complement -100 = ? PITT CS 1621
Primitive Data Types: Floating Point • Model real numbers, but only as approximations • Languages for scientific use support at least two floating-point types • float and double • IEEE Floating-Point Standard 754 or, mantissa PITT CS 1621
00000000000000000000000000000001 00000000011111111111111111111111 00000000100000000000000000000000 01111111011111111111111111111111 Range of numbers • Normalized (positive range; negative is symmetric) • Unnormalized smallest +2-126×(1+0) = 2-126 largest +2127×(2-2-23) smallest +2-126×(2-23) = 2-149 largest +2-126×(1-2-23) 2-126 2127(2-2-23) 0 2-149 2-126(1-2-23) Positive overflow Positive underflow PITT CS 1621
In comparison • The smallest and largest possible 32-bit integers in two’s complement are only -232 and 231- 1 • How can we represent so many more values in the IEEE 754 format, even though we use the same number of bits as regular integers? what’s the next representable FP number? 2-126 2127×(2-2-23) 0 2-149 differ from the smallest number by 2-149 +2-126×(1+2-23) PITT CS 1621
Representation Errors • (0.2)10 = 1.100110011001100110011010 × 2^(-3) • if (0.1 + 0.2) == 0.3 returns false • 0.1+0.2 = 0.30000000000000004 • Two operands shouldn’t be too different • (1.418 + 2937) – 2936 = 2938 – 2936 = 2.000 • 1.418 + (2937 – 2936) = 1.418 + 1.000 = 2.418 PITT CS 1621
Primitive Data Types: Decimal • For business applications (money) • Essential to COBOL • C# offers a decimal data type • Using 4 bits to store one decimal number • BCD representation • Evaluation: • Advantage: accurate computation in range • Comparing to floating point number • Disadvantages: limited range, wastes memory PITT CS 1621
Primitive Data Types: Boolean • Simplest of all • Range of values: two elements • one for “true” and one for “false” • Could be implemented as bits, but often as bytes • Advantage: readability PITT CS 1621
Primitive Data Types: Character • Stored as numeric codings • Most commonly used coding: ASCII • American Standard Code for Information Interchange • An alternative, 16-bit coding: Unicode • Includes characters from most natural languages • Originally used in Java • C# and JavaScript also support Unicode PITT CS 1621
Character String Types • Values are sequences of characters • Design issues: • Is it a primitive type or just a special kind of array? • Should the length of strings be static or dynamic? PITT CS 1621
Character String Types Operations • Typical operations: • Assignment and copying • Comparison (=, >, etc.) • Catenation • Substring reference • Pattern matching PITT CS 1621
Character String Type in Certain Languages • C and C++ • Not primitive • Use char arrays and a library of functions • strcpy(src, dest) may cause buffer overflow problem • Java • String class: primitive type • StringBuffer class: changeable/mutableWhich one is more efficient? …. A popular interview question String str1 = new String(“hello,”); str1 += “the world”; StringBuffer str1 = new StringBuffer(“hello,”); str1.apend(“the world”); … and what is the difference from StringBuilder? PITT CS 1621
Jave String/StringBuffer/StringBuilder • String • is immutable, final, thread-safe, • Is stored in string pools • “==” comparison if same instance; “euqals()” comparison • “+” implemented using StringBuffer or StringBuilder • StringBuffer • Mutable, with synchronization • Convert to String by toString() method • StringBuilder • Mutable, no synchronization, added in JDK 5 • Performs better PITT CS 1621
Character String Type in Certain Languages • SNOBOL4 (a string manipulation language) • Primitive • Many operations, including elaborate pattern matching PITT CS 1621
Character String Length Options • Three options: • Static: COBOL, Java’s String class • Limited Dynamic Length: C and C++ • In C-based language, a special character is used to indicate the end of a string’s characters, rather than maintaining the length • Dynamic (no maximum): SNOBOL4, Perl, JavaScript • Ada supports all three string length options PITT CS 1621
Character String Type Evaluation • Aid to writability • As a primitive type with static length, they are inexpensive to provide--why not having them? • Dynamic length is nice, but is it worth the expense? PITT CS 1621
Character String 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/de-allocation is the biggest implementation problem Compile-time descriptor for static strings Run-time descriptor for limited dynamic strings PITT CS 1621
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 • Examples: primitive ordinal types in Java • integer • char • boolean PITT CS 1621
Enumeration Types • All possible values, which are named constants, are provided in the definition C# example enum days {mon, tue, wed, thu, fri, sat, sun}; • Design issues • Is an enumeration constant allowed to appear in more than one type definition, and if so, how is the type of an occurrence of that constant checked? • Are enumeration values coerced to integer? • Any other type coerced to an enumeration type? PITT CS 1621
Evaluation of Enumerated Type • Aid to readability • Use day name instead of a number • Aid to reliability: avoid errors • Ada, C#, and Java 5.0 provide better support for enumeration than C++ • No arithmetic operations are legal on enumeration types days d1, d2; d1 + d2 =? • No enumeration type variables are not coerced into integer types days d1; d1 = 4; ? • Enumeration variable can be assigned a value outside its defined range days d1; /*days is in range 0..6*/ d1 = 10; ? PITT CS 1621
Subrange Types • An ordered contiguous subsequence of an ordinal type Example: 12..18 is a subrange of integer type • Ada’s design type Days is (mon, tue, wed, thu, fri, sat, sun); subtype Weekdays is Days range mon..fri; subtype Index is Integer range 1..100; Day1: Days; Day2: Weekday; Day2 := Day1; PITT CS 1621
Subrange Evaluation • Aid to readability • Make it clear to the readers that variables of subrange can store only certain range of values • Reliability • Assigning a value to a subrange variable that is outside the specified range is detected as an error PITT CS 1621
Implementation of User-Defined Ordinal Types • Enumeration types are implemented as integers • Subrange types are implemented like the parent types with code inserted (by the compiler) to restrict assignments to subrange variables PITT CS 1621
Array Types • 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. Example: int a[100]; • Design issues • What types are legal for subscripts? • Are subscripting expressions in element references range checked? • When are subscript ranges bound? • When does allocation take place? • What is the maximum number of subscripts? • Can array objects be initialized? • Are any kind of slices allowed? PITT CS 1621
Array Indexing • Indexing or subscripting • Mapping from indices to elements a(index_value) an element • Syntax: FORTRAN, PL/I, Ada use parentheses, others use brackets • Index Types • Integer type only: Fortran, C, Java • Any ordinal type: Pascal • Integer or enum: Ada • Index range check • No: C, C++, Perl, Fortran • Yes: Java, ML, C# PITT CS 1621
Array Categories • Determined by the binding of the subscript type to an array element int a[?]; • Static: subscript ranges are statically bound and storage allocation is static (before run-time) • Advantage: efficiency (no dynamic allocation) func1() { static int a[100]; … } PITT CS 1621
Array Categories • Fixed stack-dynamic: • Subscript ranges are statically bound, but • The allocation is done at declaration elaboration time during execution • Advantage: space efficiency • Stack-dynamic: • Subscript ranges are dynamically bound, and • The storage allocation is dynamic (done at run-time) • Advantage: flexibility (the size of an array need not be known until the array is to be used) examples: C: func1 (int x) Ada: func_get(list_length) { declare int a[100]; list: array (1..length) of Integer } begin … end PITT CS 1621
Array Categories • Fixed heap-dynamic: • storage binding is dynamic but fixed after allocation (i.e., binding is done when requested and storage is allocated from heap, not stack) • Heap-dynamic: • binding of subscript ranges and storage allocation is dynamic and can change any number of times • Advantage: flexibility (arrays can grow or shrink during program execution) • Examples: • Java and C#: fixed heap-dynamic: func(int p1) { int[] aLst = new int[p1]; } heap-dynamic: ArrayList intLst = new ArrayList(); intLst.add(2); • Perl and Javascript heap-dynamic: @list = ( 1, 2, 3, 4); push(@list, 5, 6); PITT CS 1621
Array Initialization • Some language allow initialization at the time of storage allocation • C, C++, Java, C# example int list [] = {4, 5, 7, 83} • Character strings in C and C++ char name [] = “freddie”; • Arrays of strings in C and C++ char *names [] = {“Bob”, “Jake”, “Joe”]; • Java initialization of String objects String[] names = {“Bob”, “Jake”, “Joe”}; PITT CS 1621
Array Operations • Can we operate on an array as a unit? • Ada: assignment, concatenation, relational operations • Fortran: elemental operations that operate between pairs of elements assignment, arithmetic, relational, logical operations • APL: provides most powerful operations A +. B • Java: assignment, clone double[] data = new double[10]; double[] prices1 = data; double[] prices2 = (double[])data.clone(); PITT CS 1621
Rectangular and Jagged Arrays • A rectangular array is a multi-dimensioned array in which • all rows have the same number of elements and • all columns have the same number of elements • A jagged matrix has rows with varying number of elements • Possible when multi-dimensioned arrays actually appear as arrays of arrays C#: int[,] r2 = new int[,] {{1, 2, 3}, {4, 5, 6}}; int[][] j2 = new int[3][]; j2[0] = new int[] {1, 2, 3}; j2[1] = new int[] {1, 2, 3, 4, 5, 6}; j2[2] = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9}; PITT CS 1621
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 • Fortran 95 Integer, Dimension (10) :: Vector Integer, Dimension (3, 3) :: Mat Integer, Dimension (3, 3) :: Cube Vector (3:6) is a four element array PITT CS 1621
Implementation of Arrays • Access function maps subscript expressions to an address in the array • Access function for single-dimensioned arrays: PITT CS 1621
Accessing Multi-dimensioned Arrays • Two common ways: • Row major order (by rows) – used in most languages • column major order (by columns) – used in Fortran PITT CS 1621
Row Major PITT CS 1621
Column Major PITT CS 1621
Generalized Row/Column Major PITT CS 1621
C’s Implementation PITT CS 1621
Compile-Time Descriptors Single-dimensioned array Multi-dimensional array PITT CS 1621
Runtime Descriptor ? • What do you need? …..a[i] … Conceptually … if( i < upperBound) …a[0] + i*width… /*i: variable*/ PITT CS 1621
Problem to Solve • Which is more efficient? • Assume there is no grammar mistake #define LEN 100 int arr1*; int arr3[LEN]; function f1( int NewLen) { int arr2[NewLen]; int @arr4 = { 1,2,3,4,5,6,7}; @arr4 = (9,8,@arr5); arr1 = malloc(NewLen); } PITT CS 1621
Associative Arrays • An associative array is an unordered collection of data elements that are indexed by an equal number of values called keys • User defined keys must be stored • Design issues: What is the form of references to elements Perl: %htemp =("Mon" => 77, "Tue" => 79, “Wed” => 65, …); $hi_temps{"Wed"} = 83; delete $hi_temps{"Tue"}; PITT CS 1621
Record Types • A record is a possibly heterogeneous aggregate of data elements in which the individual elements are identified by names • Design issues: • What is the syntactic form of references to the field? • Are elliptical references allowed? PITT CS 1621
Records Definitions • Introduced by COBOL in 1960s • Syntax COBOL 01 EMP-REC. 02 EMP-NAME. 05 FIRST PIC X(20). 05 MID PIC X(10). 05 LAST PIC X(20). 02 HOURLY-RATE PIC 99V99. Ada type Emp_Rec_Type is record First: String (1..20); Mid: String (1..10); Last: String (1..20); Hourly_Rate: Float; end record; Emp_Rec: Emp_Rec_Type; PITT CS 1621
More about Records • References • Most language use dot notation Emp_Rec.Name • Fully qualified references must include all record names • Elliptical references allow leaving out record names as long as the reference is unambiguous, for example in COBOL • Operations on Records • Assignment is very common if the types are identical • Ada allows record comparison • Ada records can be initialized with aggregate literals • COBOL provides MOVE CORRESPONDING • Copies a field of the source record to the corresponding field in the target record PITT CS 1621
Evaluation • Straight forward and safe design • Comparison to Arrays • Access to array elements is much slower than access to record fields, because subscripts are dynamic (field names are static) a[i] and b.field1 • Dynamic subscripts could be used with record field access • but it would disallow type checking and it would be much slower PITT CS 1621