Types (different views) Value collection values having the same - - PowerPoint PPT Presentation

types different views
SMART_READER_LITE
LIVE PREVIEW

Types (different views) Value collection values having the same - - PowerPoint PPT Presentation

Types (different views) Value collection values having the same properties can be collected together e.g. integers, floating points different representations for different types operations allowed for a type controlling


slide-1
SLIDE 1

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

1

Types (different views)

  • Value collection

– values having the same properties can be collected together

  • e.g. integers, floating points

– different representations for different types

  • operations allowed for a type
  • controlling the way how values are used
  • Type construction

– more complicated types can be created from the primitive ones with a type constructor – value set and operations are seen as natural features for a type

  • Type abstraction

– types as interfaces (modules, classes)

  • implementation details hidden

– values can be accessed via predefined operations

slide-2
SLIDE 2

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

2

Desing issues for types

  • Is type a static or dynamic concept?

– are the properties of a type known already at compile time or only at run time

  • Are types of variables bound

statically or dynamically?

  • Are parametrized types enabled?

– are these parameters static or dynamic – which parts of a type declaration can be parametrized

  • How to define type equivalence?

– on which conditions two variables have the same or compatible types

var X: Integer; ... type T = array [ 1..X ] of Integer; type T ( Max: Integer ) = 1..Max; ... var A: T ( 10 ); procedure P ( X: Integer ); var A: T ( X ); ... Example codes written in an imaginary language

slide-3
SLIDE 3

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

3

Strong typing

  • A programming language is strongly typed if

– each data item (constant, variable, field) has a unique type, the identity and properties of which are known at compile time – type conversions are controlled by interpreting the value as a value of another type

  • not by interpreting the value presentation as a value presentation
  • f another type
  • legality of type conversions must be known at compile time
  • Static typing

– type of each variable is known at compile time

  • Strong typing -> static typing

Other definitions:

  • type errors are detected (at compile time or run time)
  • operations not supported by a type are prevented
slide-4
SLIDE 4

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

4

  • Allowing implicit type conversions makes the

typing of the language less stronger

  • Type cast

– occurs explicitly

  • Coersion

– occurs implicitly

Type conversions

int a; float d; d = ( float ) 6; a = ( int ) 7.5; int a, b; float d; … a = a + d;

What if this is a misspelling? The programmer intended to write ”a = a + b;”

slide-5
SLIDE 5

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

Type conversions vs. strong typing

  • Stronger typing (Ada)

− explicit conversions allowed only in a limited sense − exception: Unchecked_conversion

  • Weaker typing (C)

− compiler can make automatic type coersions − lack of consistency

  • when and what kind of coersions take place
  • when an explicit conversion is possible
slide-6
SLIDE 6

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

6

Typing in programming languages

  • Fortran (weak typing)

– types are not checked in parameter passing – Equivalence statement

  • Pascal (nearly strong typing)

– variant records are not necessarily safe

  • Ada (strong typing)

– variant records are safe – type conversions are controlled

  • C and C++ (weak typing)

– type checking is not compulsory in parameter passing – unions are not safe – coercions allowed

  • Java and C# (strong typing)
slide-7
SLIDE 7

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

7

Type equivalence (compatibility)

  • Name type equivalence

– the name of the type identifies the type – types with different names are different types – each nameless type is different from other types

  • Structure type equivalence

– the name of the type is a shorthand of the type definition – two types are same, if they have the same structure and each component in the structure has the same type or identifical definition

  • Both equivalences can be applied to both scalar types and

structural types

typedef int weight; typedef int length;

C-code:

slide-8
SLIDE 8

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

8

Examples on type equivalence

var X: array [ 1..10 ] of Integer; Y: array [ 1..10 ] of Integer; var X, Y: array [ 1..10 ] of Integer; type T = array [ 1..10 ] of Integer; U = array [ 1..10 ] of Integer; var X : T; Y: U; type T = array [ 1..10 ] of Integer; U = T; var X: T; Y: U;

Examples are written in Pascal

slide-9
SLIDE 9

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

9

More examples on type equivalence

Pascal-code:

const C = 10; type T = array [ 1..10 ] of Integer; R = record E: Integer; D: array [ 1..C ] of Integer; end; var X: record A: Integer; B: T; end; Y: R; var X: array [ 1..10 ] of Integer; Y: array [ 2..11 ] of Integer; Z: array [ 1..2*5 ] of Integer;

slide-10
SLIDE 10

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

10

An algorithm to solve structure type equivalence

1. Take two type definitions. 2. In both type definitions, replace each type name with the corresponding type definition. 3. Repeat step 2 until there are no type names (except standard types like integer, float, and so

  • n) in the type definitions.

4. Compare the resulting type definitions as texts. Identical definitions are equivalent types.

slide-11
SLIDE 11

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

11

Benefits of name type equivalence (vs. structure type equivalence)

  • Easier to implement
  • Support for safety (error detection)
  • Support for type abstraction
  • Increases readability and understandability

(named types)

slide-12
SLIDE 12

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

12

Type equivalence in programming languages

  • Name type equivalence

– Java – Ada (except for named subtypes) – C++ (except for typedef)

  • Structure type equivalence

– Algol68 and Modula-3 – C

  • e.g. typedef does not create a new type
  • except for record types (struct, union)

typedef int weight; typedef int length;

slide-13
SLIDE 13

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

Type inference

  • Violations of type consistency can be checked

at compile time

  • Consistency checkings (ML):

− all occurences of the same identifier must have the same type − if x then E1 else E2

  • type of x is boolean
  • E1 and E2 have the same type

− type of a function (’a -> ’b)

E1: ’a * int E2: string * ’b What can be inferred?

slide-14
SLIDE 14

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

Type inference and polymorphism

fun compare ( x, p, q ) = if x = p then if x = q then ”both” else ”first” else if x = q then ”second” else ”neither” Type of (=): ’a * ’a -> bool Type of compare: ’a * ’a * ’a -> string

slide-15
SLIDE 15

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

15

Types in programming languages

  • Scalar types
  • Enumerated types
  • Subrange types, subtypes, derived types
  • Structured types

– formed with a type constuctor (array, record)

  • Pointer (and reference) types
  • Set types
  • Subprogram and function types

– will be introduced in the context of subprograms

  • Task types (Ada)

– associated with concurrency, will be introduced in this context

slide-16
SLIDE 16

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

16

Scalar types (primitive types, atomic types)

  • Numeric types

– integers – floating points – decimal numbers

  • Logic type

– boolean

  • Character type
  • Ordinal types

– each value has a predecessor and successor (except for the minimum and maximum values) – includes enumerated types

  • Other types

– floating points – decimal numbers

Division 1: Division 2:

slide-17
SLIDE 17

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

17

Numeric types

  • Representation of a numeric value

– it is most efficient to use the internal representation of a computer – variations in the representation make portability harder

  • Representation of integers: two’s complement

– 2n-1..2n-1-1 e.g. 16 bits: -32768..32767

  • Representation of floating points:

– follows a standard (that is a compromise)

  • adding bits for fraction would increase precision
  • adding bits for exponent would increase range
  • Decimal numbers (Cobol, C#)

– fixed number of decimal digits, decimal point at a fixed position – precision is high, range is restricted

Integers are used as

  • mathematical value
  • loop counter
  • array index

s exponent fraction 1 8 23

slide-18
SLIDE 18

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

18

Logic types

  • Two values: true and false

– could be represented with a single bit – however it is more practical to reserve a whole byte

  • Included in most languages, not in C

– typically used to represent switches or flags – increase readability

  • Two kinds of boolean operators:

– (traditional) logical operator – bit-wise operator

#define bool short int #define TRUE 1 #define FALSE 0

slide-19
SLIDE 19

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

19

Character type

  • Common operations:

– equivality, lexicografical ordering – I/O – conversions to string type and back – upper to lower case and back

  • Internal representation in the memory

– old encodings (EBCDIC in IBM computers) – ASCII (ISO-646) (7 bits), ISO-latin (8 bits) – Unicode (32 bits) (previously also 16-bit version)

slide-20
SLIDE 20

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

20

Issues with character type

  • Size of characters and interpretation of the numeric

value

– often 8 bits, max. 256 characters

  • not enough for non-English languages

– solution 1: several encodings (ISO-latin-X) – solution 2: larger type (Unicode)

  • What determines the encoding?

– source file encoding (character and string literals, identifiers) – memory representation (internal encoding of the program)

  • Conversions with I/O

– between the internal encoding and that of the user

slide-21
SLIDE 21

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

21

Design issues of characters

  • Comparison

– what determines alphabetical order

  • is it the same as character comparisons < and >

– when are characters the same

  • One or many characters?

– ligature: ß, ij, ŋ, ä – upper/lower case problems: ß -> SS – several representations: ä (U+00E4) vs. ä = a¨ (U+0061, U+00A8)

  • Does the language support several encodings?

– several types: trouble – one type: needs to be large enough (Unicode) – downwards compatibility issues

slide-22
SLIDE 22

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

22

String type

  • Traditional: list/array of characters
  • Typical operations:

– indexing – slicing – printing – concatenation

  • How to encode?

– character type problems remain

  • 32 bits/character would quadruple memory

consumption

slide-23
SLIDE 23

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

23

Unicode and strings

  • Standard encoding for about 128 000 characters

(encoding allows 1 114 112)

  • Codes U+000000 – U+10FFFF for characters
  • Part of the codes reserved for other purposes
  • String encoding UTF-32 (UCS-4)

– string is a sequence of 32-bit characters – easy, directly indexable – lots of memory consumed, wasted bits

slide-24
SLIDE 24

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

24

String encoding UTF-16

  • String consists of 16 bits (a pair of bytes) at least
  • Unicode symbols ≤ U+FFFF are coded directly
  • Rests are presented by surrogates, two pairs of 16 bits
  • Surrogates are encoded so that first and second code

cannot be confused

  • Consequence 1:

– it can be immediately checked if a pair is a character, a surrogate beginning, or a surrogate ending

  • Consequence 2:

– symbols may be one or two pairs of bytes!

slide-25
SLIDE 25

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

25

String encoding UTF-8

  • 8-bit bytes form a symbol
  • Unicode symbols ≤ U+7F are coded directly (7-bit ASCII)
  • Rest up to ≤ U+7FF use 2 bytes (European characters)
  • Rest up to ≤ U+FFFF use 3 bytes (Asian characters)
  • Rest use 4 bytes (old languages, math symbols, …)
  • Consequence:

– symbols are 1-4 bytes!

  • Multibyte symbols can be separated from 1-byte symbols

and so on

  • Consequence:

– bytes can be scanned until beginning of a symbol is found

slide-26
SLIDE 26

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

26

Unicode: problems in indexing (UTF-8 and UTF-16)

  • Symbols differ in size

– s [ i ] is not the (i + 1)th symbol!

  • String length and table size are not the same!
  • Indexing at the middle of a symbol
  • Replacing a symbol is complicated if of different

size

– encoding using strings is complicated

  • Unicode iterator: returns unicode symbols and

moves correctly in a string

slide-27
SLIDE 27

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

27

Unicode challenges

  • More memory and cache (especially UTF-32)
  • Alphabets

– number-coded alphabetizing impossible

  • Equality

– strings must be normalized before comparing

  • Conversions are needed if multiple codings are

supported

slide-28
SLIDE 28

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

28

Unicode in some languages

  • Java

– string coding UTF-16 – source code coding UTF-8

  • Python

– strings ”raw” and Unicode – source code can present what coding is used

  • C++

– C++03: not defined (wchar_t = UTF-32?) – C++11: support for UTF-8/16/32, but not full – source code coding depends on the compiler

slide-29
SLIDE 29

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

29

Enumerated types

  • Value range (possible values) define the type
  • Collection of named constants
  • Design issues:

– is it possible for an enumerated constant to occur in several type declarations, and in positive cases, how the type checkings are made? – are enumerated values automatically interpreted as integers? – is it possible to interpret the values of other types to the values of enumerated type?

slide-30
SLIDE 30

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

30

Examples of enumerated types

type colors = ( red, blue, green, yellow, black ); enum colors { red, blue, green, yellow, black }; colors myColor = blue; ... myColor++; /* allowed */ myColor = 4; /* forbidden */ Pascal: C++: Java: public enum colors { red, blue, green, yellow, black }

slide-31
SLIDE 31

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

31

Subrange types (in Pascal)

  • Do not create an own type

– types derived from the same base type are compatible with each other and with the base type – unsafe

  • Implemented like the base type

– additional range check type Year = 1000..3000; Weight = 0..5000; var y: Year; w: Weight; ... y := w; y := y + w; type Day = ( mon, tue, wed, thu, fri, sat, sun ); WeekDay = mon..fri;

slide-32
SLIDE 32

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

32

Subtypes (Ada)

  • A limit on legal values, not an independent type
  • Named subtype benefits:

– limitations do not have to be repeated, if subtype is used for several variables – when limits are changed, only one place needs to change – single identifier improves readability – more efficient implementation

X: Integer; ... subtype R is Integer range 1..X; subtype SmallInt is Integer range -100..100; subtype MicroInt is SmallInt range -10..10;

slide-33
SLIDE 33

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

Derived types (Ada)

  • Creates an own type that is not compatible

with other types (not even with the base type)

type Color is ( Red, Yellow, Green, Black, White ); type TrafficLight is new Color range Red..Green; c: Color; t: TrafficLight; ... c := Red; t := Red; ... if Red < Green then ...

  • - wrong

if Color’(Red) < Green then ... -- right

slide-34
SLIDE 34

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

34

Arrays

  • Ordered collection of data having the same type
  • Array type declaration includes:

– name of the array type (or an unnamed type) – element type – index type (range = size of the array)

  • Indexes (subscripts)

– essential operation for arrays – brackets or parentheses Vector Matrix

slide-35
SLIDE 35

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

35

Design issues of arrays

  • Which types are legal for subscripts?

– subrange of integer – character, enumerated type, boolean

  • Are subscript expressions range-checked?
  • When are subscript ranges bound?
  • When does array allocation take place?
  • Can arrays be initialized when they have their

storage allocated?

  • Which kinds of slices are allowed, if any?
slide-36
SLIDE 36

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

36

Variable categories according to lifetime (how to apply to array variables)

  • Static variables

– bound to memory location before program execution – binding is preserved through the whole execution

  • Stack-dynamic variables

– bound to memory location during elaboration of their declaration – type is bound statically

  • Explicit heap-dynamic variables

– bound to a memory location according to programmer’s instructions – variables are referenced via pointers (no name) – type is bound statically

  • Implicit heap-dynamic variables

– bound to memory location when values are assigned global variables static (in C) local variables pointer variables variables in script languages

slide-37
SLIDE 37

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

37

Lifetime category for arrays (1/2)

  • Static arrays

– memory space allocated statically – subscript ranges are statically bound

  • Fixed stack-dynamic arrays

– memory allocation is done at declaration elaboration time during execution – subscript ranges are statically bound – e.g. C/C++ local arrays (without static-declaration)

  • Flexible stack-dynamic arrays

– memory space allocated dynamically – subscript ranges are dynamically bound, but remain fixed during the lifetime of the variable – e.g. Ada Len: Integer; Get ( Len ); declare List: array ( 1..Len ) of Integer; begin ... end;

slide-38
SLIDE 38

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

38

Lifetime category for arrays (2/2)

  • Fixed heap-dynamic arrays

– memory space allocated dynamically – subscript ranges are dynamically bound, but remain fixed during the lifetime of the variable – memory space is allocated according to programmer’s commands – e.g. Java, C#

  • Flexible heap-dynamic arrays

– allocated memory space and subscript ranges may vary during the lifetime of the variable – e.g. Perl, JavaScript, ArrayList in C#

ArrayList intList = new ArrayList ( ); intList.Add ( nextOne ); @list = ( 1, 2, 3, 4 ); push ( @list, 5, 6 ); Java: Perl: a = new int [ size ];

slide-39
SLIDE 39

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

39

Array initialization

int int_array [ 3 ] = { 3, 5, 8 }; type vector is array ( 1..6 ) of integer; a: vector; a := ( 7, 0, 7, 0, 0, 0 ); a := ( 1 => 7, 2 => 0, 3 => 7, 4..6 => 0 ); a := ( 1 | 3 => 7, others => 0 ); Aggregate: C: Ada: int int_array [ ] = { 3, 5, 8 };

slide-40
SLIDE 40

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

40

Associative arrays

  • Conventional arrays

– array elements have an implicit order – array indexes are not stored

  • Associative arrays

– unordered set of elements – each element is associated with a key that is used when referencing the element – key values are stored – e.g. Perl

slide-41
SLIDE 41

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

41

Array implementation (one-dimensional)

address ( list [ k ] ) = address ( list [ 1 ] ) + ( k – 1 ) * element_size = ( address ( list [ 1 ] ) – element_size ) + ( k * element_size )

list [ k ] Index type Index lower bound Element type Index upper bound Elements Array (type name) Descriptor

slide-42
SLIDE 42

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

42

Array implementation (multidimensional)

Index type Element type Index range 1 ... Array (type name) Index range n Elements 3 4 7 6 2 5 1 3 8 row major order: 3 4 7 6 2 5 1 3 8 column major order: 3 6 1 4 2 3 7 5 8

1 2 ... j-1 j ... n 1 2 .. i-1 i ... m

slide-43
SLIDE 43

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

43

Character strings revisited

  • Implementation issues:

– can be implemented as an array, the elements of which are characters, or as an own type – is the length of a string static or dynamic

Type name Length Address Type name Maximum length Current length Address

Static string Limited dynamic string

slide-44
SLIDE 44

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

44

S u n d a y \ M o n d a y \ T u e s d a y \ W e d n e s d a y \ T h u r s d a y \ F r i d a y \ S a t u r d a y \

char days [ ] [ 10 ] = { ”Sunday”, ”Monday”, ”Tuesday”, ”Wednesday”, ”Thursday”, ”Friday”, ”Saturday” }; ... days [ 2 ] [ 3 ] == ’s’;

S u n d a y \ M o n d a y \ T u e s d a y \ W e d n e s d a y \ T h u r s d a y \ F r i d a y \ S a t u r d a y \

char *days [ 10 ] = { ”Sunday”, ”Monday”, ”Tuesday”, ”Wednesday”, ”Thursday”, ”Friday”, ”Saturday” }; ... days [ 2 ] [ 3 ] == ’s’;

Contiguous allocation Row pointers

C-code: C-code:

slide-45
SLIDE 45

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

45

Arrays and strings (Pascal)

  • Fixed subscripts

– arrays of different size have different type

  • character strings
  • array parameters
  • Strings are arrays the elements of which are characters

– unflexibility – packed arrays increase flexibility (a little)

  • assignment, printing, comparison

type Table1 = array [ 1..100 ] of Integer; Table2 = array [ 1..500 ] of Integer; ... procedure Sort1 ( var x: Table1 ); procedure Sort2 ( var x: Table2 );

Historical perspective

slide-46
SLIDE 46

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

46

type list is array ( Integer range <> ) of Real; b: list ( 1..20 ); c: list ( 1..1000 ); function sum ( a: list ) return real is total: real := 0.0; begin for i in a’Range loop total := total + a ( i ); end loop; return total; end sum; FUNCTION sum ( a: ARRAY OF Real ): Real; VAR i: Integer, total: Real; BEGIN total := 0.0; FOR i := LOW ( a ) TO HIGH ( a ) DO total := total + a [ i ]; sum := total; END;

Modula-2 Ada

Open array parameters

Historical perspective

slide-47
SLIDE 47

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

47

Records

  • Heterogenious structure

– components (fields) may have different types – component is referenced with its name

  • Components (fields) can be records

– hierarchical tree structure

  • Record type declaration includes:

– record type name (or an unnamed type) – field names and their types

  • Operations:

– assignment – comparison operations (equal, unequal)

Record Name Type Offset ... Name Type Offset Address

  • 1. field
  • n. field
slide-48
SLIDE 48

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

48

Record operations

  • Referencing to a field
  • Assigning values to fields
  • Pascal’s

with statement:

record.field field ( record )

The most common way: Algol68:

person := ( first_name => ”Matti”, last_name => ”Virtanen” ); person := ( ”Matti”, ”Virtanen” );

type complex = record re: real; im: real; end; var x: complex; with x do begin re := 1.5; im := 2.0; end;

Ada:

slide-49
SLIDE 49

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

49

Record discriminant in Ada

  • Parametrization of the record definition
  • Discriminants are also used in selectors for variant

records

type Complex ( real_init, imag_init: Float ) is record re: Float := real_init; im: Float := imag_init; end record; C: Complex ( 0.0, 1.0 ); D: Complex ( real_init | imag_init => 0.0 ); Formal parameters Actual parameters

slide-50
SLIDE 50

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

50

Variant records

  • A single field can store values of different types at

different times

– types vary during execution

  • Type checking of the variant field

– Ada: discriminant – Pascal: tag (optional)

  • No type checking

– C/C++: free unions Safety issue important in strong typing

slide-51
SLIDE 51

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

51

Variant records or unions in C

typedef union { char car [ ]; int bicycles; } garage; garage my_garage; my_garage.car = ”Trabant”; printf ( ”%d\n”, my_garage.bicycles );

slide-52
SLIDE 52

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

52

Variant records in Ada

type owner_type is ( car_freak, bike_freak ); type garage ( owner: owner_type ) is record case owner is when car_freak => car: String; when bike_freak => bicycles: Natural; end case; end record; my_garage: garage; my_garage := ( owner => car_freak, car => ”Porsche” );

  • - could not pay for it

my_garage.car := ”VW”;

  • - changed my way of life

my_garage := ( owner => bike_freak, bicycles => 8 );

Discriminant = record parameter Type checking occurs either at compile time or at run time

slide-53
SLIDE 53

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

53

Safety of variant records in Ada

  • Static discriminant

– correctness of field references can be checked at compile time

  • Dynamic discriminant

– checked at run time:

  • wn: owner_type;

biker: garage ( bike_freak ); ...

  • wn := ... ;

declare x: garage ( own ); ... x := biker;

  • k, if own = bike_freak

(run time check)

slide-54
SLIDE 54

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

54

Variant records in Pascal

  • Safety deficiencies (like in C)

– cannot be sure that references are made to existing fields only

type owner_type = ( car_freak, bike_freak ); garage = record case owner_type of car_freak: ( car: packed array ...); bike_freak: ( bicycles: Integer ); end; type owner_type = ( car_freak, bike_freak ); garage = record case owner_tag: owner_type of car_freak: ( car: packed array ...); bike_freak: ( bicycles: Integer ); end;

  • wner_type
  • wner_tag: owner_type
slide-55
SLIDE 55

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

55

Variant records in Pascal

  • Standard implementation assumes an imaginary

tag-field, if it is not given in the type definition

– most implementations do not follow the standard

x: garage; ... if ... then [ x.tag := car_freak; ]

  • x. car := ’...’;

else [ x.tag := bike_freak; ] x.bicycles := 4; ... [ if x.tag <> bike_freak then ERROR; ] if x.bicycles = 3 then ...

type owner_type = ( car_freak, bike_freak ); garage = record case owner_type of car_freak: ( car: packed array ...); bike_freak: ( bicycles: Integer ); end;

slide-56
SLIDE 56

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

Implementation of variant records

type owner_type is ( car_freak, bike_freak ); type garage ( owner: owner_type ) is record area: Float; case owner is when car_freak => car: String; model: Natural; when bike_freak => bicycles: Natural; end case; end record;

area

  • wner

car model bicycles

slide-57
SLIDE 57

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

57

Pointer type

  • Range for pointer type

– value is a memory address – special value (nil, null)

  • Operations

– value assignment – comparison (equal, unequal) – dereference

  • Pointer arithmetic (in C)

– assigning a constant value (e.g. 0xCE00) to a pointer variable – adding an integer to a pointer variable – subtraction between two pointer variables heap-dynamic variables 0x0804a008 2148 0x0804a865 0x0804a008 ptr ptr == 0x0804a008 *ptr == 2148 2148 0x0804a963 j j = *ptr;

slide-58
SLIDE 58

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

58

Pointer reference and dereference

References to record fields: ptr: reference => 0x0804a008 dereference => 2148 C: (*p).age p->age Pascal: p^.age Ada: p.age

0x0804a008 2148 0x0804a865 0x0804a008 ptr

slide-59
SLIDE 59

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

59

Benefits of pointers

  • Memory allocation and deallocation are flexible (not

bound to a program structure)

  • The same memory location can be referenced by

several pointers/names

– aliasing – can also cause problems

  • The content of the memory location need not be

copied

– e.g. in passing large parameters

  • Pointers provide a natural way to implement recursive

data structures

int i, *ptr; i = 34; ptr = &i; 34 ptr i ptr &i *ptr i

slide-60
SLIDE 60

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

60

Pointers in C and C++

  • Dangling pointers are potential
  • Pointer arithmetics
  • Pointers and arrays are related

int list [ 10 ]; int *ptr; ptr = list; * ( ptr + 1 ) ⇔ list [ 1 ] * ( ptr + index ) ⇔ list [ index ]; ptr [ index ] ⇔ list [ index ];

slide-61
SLIDE 61

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

61

Reference type

  • Differs from pointers:

– refers to an object or a value, not an address (like a pointer)

  • C++ reference type (marked with &)

– constant pointer

  • always implicitly dereferenced

– typically used in formal parameters

  • Java reference type

– replaces pointer type entirely – not constants

  • can be assigned to refer to different

class instances

61

int a = 0; int &a_ref = a; void duplicate ( int &i ) { i = i * 2; } ... int x = 2; duplicate ( x ); // x ← 4 void duplicate ( int *i ) { *i = *i * 2; } ... int x = 2; duplicate ( &x ); // x ← 4

C++ C

slide-62
SLIDE 62

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

Set type

  • Operations

− union − intersection − difference (subtraction) − symmetric difference (exclusive or, XOR) − member: does an element belong to a set

  • Implementation

− most common way: bit vector

  • 1 in position k: kth element of the base type belongs to the set
  • 0 in position k: kth element does not belong to the set

  • ther ways: array, hash table

TYPE Digit = [ 0..9 ]; DigitSet = SET OF Digit;

Modula-2:

{ 0, 3, 5 } 1 0 0 1 0 1 0 0 0 0