COSC 2P90 TYPES, VALUES AND DECLARATIONS (c) S. Thompson, M. Winters 1
Names, References, Values & Types data items have a value and a type type determines set of operations variables Have an identifier (name) Have a storage location Has attributes binding diagram (Barron) name reference value identifiers allowable characters E.g. Perls $,@,% (scalar, array, hash) prefixes length case sensitivity naming conventions Underscore (buffer_size) vscapitlization (buffersize) (c) S. Thompson, M. Winters 2
Binding Association of one property with another choice of a property from a set of possible properties name-declaration binding connection between identifier and declaration name-type binding choose type for a variable identified by a name declaration-reference binding storage allocation reference-value binding storing value of a variable (c) S. Thompson, M. Winters 3
Binding Time time at which binding occurs alternatives compile-time (e.g. name-type binding in Java) load-time (e.g. declaration-reference binding for non-local variables in C) run-time at block entry (e.g. declaration-reference binding for local variables in Java) at statement execution (e.g. reference-value binding for variables) early early error detection and efficient execution late flexibility (c) S. Thompson, M. Winters 4
Name-Declaration Binding declaration Binding Explicit variables have to be declared prior to use { int a; a = 4 + b; } Implicit - declaration occurs at first usage { a = 4; print( a ); } Connection between name and its declaration Rules for binding are referred to as scope rules (c) S. Thompson, M. Winters 5
Scope Rules Static scope at compile-time can be determined from static program text block structure block, scope, hole-in-scope local variable, non-local variable, global variable e.g. Pascal, Java Dynamic scope - at run-time Depends on the order of execution Uses a binding stack Rarely used in practice (Common lisp & perl give the choice to use it) (c) S. Thompson, M. Winters 6
Static Scope Example - Pascal program Example(input, output) var x, y : Real; Visible to entire program # procedure op1; var y, z : Integer; Visible to op1 procedure * begin... y := 34; refers to the y in * x := 27.4;... end{op1}; begin... x := 3.768; y := x; refers to the y in #... end{example}. (c) S. Thompson, M. Winters 7
Static Scope Example - Java class Example { private double x, y; public void op1() { int y, z; y := 34; x := 27.4;... } // op1 public void op2() { x := 3.768; y := x;... } // op2 } // Example (c) S. Thompson, M. Winters 8
Dynamic Scope Example (Pascal syntax) program Dynamic(input, output); var x : Integer; procedure a; begin... write(x);... end{a}; procedure b; var x : Real; begin... x := 2.0;... a;... end{b}; begin... x := 1;... b;... a;... end{dynamic}. (c) S. Thompson, M. Winters 9
Dynamic Scope Example - Perl Static Scope prints 0 $a = 0; sub b { return $a; } sub c { my $a = 1; return b(); } print c(); Dynamic scope prints 1 $a = 0; sub b { return $a; } sub c { local $a = 1; return b(); } print c(); (c) S. Thompson, M. Winters 10
Name-Type Binding specification of type for variable statically typed type is known at compile-time advantages Reliable errors are detected at compile time Efficient no type checks required at runtime Understandable type is obvious to human reader strongly-typed Variables always used in proper context weakly-typed Implicit type conversion occurs usually causes confusion on the result (c) S. Thompson, M. Winters 11
Name-Type Binding dynamically typed run-time variables don t have types, values do advantage flexibility type discovery polymorphic variables in object-oriented languages only subclass values assignable static type checking with flexibility of dynamic typing type inference (ML, Haskell) The ability to deduce a type Available commonly in functional languages (also C# 3.0 & Perl 6) (c) S. Thompson, M. Winters 12
Type Inference Example - C# class Example { void SomeMethod() { var i = 1; i is an integer var mystr = a string ; } } var is also known as an anonymous type (c) S. Thompson, M. Winters 13
Declaration-Reference Binding Refers to when the storage location for a variable is assigned 3 times when a variable can be assigned storage Load time Block entry Statement execution Lifetime (a.k.a. extent) of a variable refers to when during a program execution a variable has storage allocated to it Local variables Lifetime is only during block (method) execution void f() { int i = 0; print(i); } i only has storage while f is executed (c) S. Thompson, M. Winters 14
Declaration-Reference Binding instance variables O-O languages think member variables of a class allocated at statement execution (new) as part of object Lifetime is determined by object lifetime void f() { MyClass obj = new MyClass(1,2); } (c) S. Thompson, M. Winters 15
Declaration-Reference Binding global variables allocated at load time class variables (static in Java) allocated at load time, one occurrence per class /* C */ int somevalue = 1; void SomeFunc() { somevalue = 2; } // Java class someclass { static int somevalue = 1; void SomeFunc() { somevalue = 2; } (c) S. Thompson, M. Winters 16
Declaration-Reference Binding static and own variables procedure memory allocated at load time, but local scope void func() { static int i = 0; printf( %d, i++ ); } int main() { func(); func(); func(); Displays 0 1 2 } (c) S. Thompson, M. Winters 17
Reference-Value Binding Refers to assigning a value to a storage location Run-time at input, assignment or parameter passing Assignment ( y = y + 1 ) 3 bindings involved: name-declaration, declaration-reference, referencevalue dereferencing l-value (can store) vs r-value (read only) Language without an assignment statement it may have immediate name-value binding pure functional languages (c) S. Thompson, M. Winters 18
Reference-Value Binding Uninitialized variables How to deal with this problem? Initialize during declaration Error to use an uninitialized variable Constants name-value binding at compile time Pascal vs Ada vs Java May be delayed until runtime (complex assignment) (c) S. Thompson, M. Winters 19
Types Everything is represented as bits The type gives interpretation A set of values and operations Three common types: scalar, structured and reference Scalar types single values Numeric (e.g. integer, floating point) Logical Character Numeric Types are either Discrete (unique successor & predecessor) Non-discrete (e.g. Real/Double) built-in/primitive types defined in language E.g. int in Java is not an object programmer-defined types type declarations (e.g. Pascal, Ada, C) class declarations (e.g. Java) (c) S. Thompson, M. Winters 20
Specifying Types Very common in languages for variables to be declared before use To either built-in or user-defined Implicit declaration Name of variable implies type (Fortran I-N prefix are Ints) Easy to make type errors through typos Type declarations associate a name with a set of type attributes modifiability, type-checking Type declarations Ada: a,b: Integer C: int a; Derived Types: Same representation but different meaning Ada: Type List is array(1..10) of Integer C: typedef List int[10]; (c) S. Thompson, M. Winters 21
Specifying Types Ada also uses subtypes Subtype is a subset of values E.g. subtype Index is Integer range 1...10; Subtypes & derived types allow programmer to reuse existing representation for new meaning Type equivalence Ada: Name Equivalence To be of the same type, the type of two variables must have the same name Each type has unique operators associated C: Structure Equivalence To be of the same type, the type of two variables must represent the same type abstract data types A type and the operations on that type Operations can be defined through functions (e.g. push & pop) O-O classes encapsulate these together modules contain type declaration class is type declaration (c) S. Thompson, M. Winters 22
Numeric Types machine representation vs standard model efficiency vs compatibility E.g. different floating point answers on different machines operators overloading: effect depends on type of operands 2+3 integer addition 2.3+4.5 floating-point addition div vs / Exponentiation Expensive omitted in some languages to emphasize this Logical results relational operators: <, >=, etc. equality operators: == or = inequality operators:!= or <> or /= integer vs fixed-point vs floating-point impact on equality (c) S. Thompson, M. Winters 23
Integer Types uses as models of Integer in Mathematics vs counting two s complement Range -2 (n-1) to 2 (n-1) -1 where n is the number of bits available Explicit vs. machine dependent ranges larger and smaller ranges C char, short, int, long (& long long) Java byte, short, int, long Pascal subranges Ada Short_Integer, Integer, Long_Integer and subranges Used in derived types and let compiler pick most appropriate (c) S. Thompson, M. Winters 24
Integer Types fixed-point types COBOL & PL/I for currency values Used on hardware with no floating-point support Useful on graphics hardware! Of N bits, M are used to represent the integral component and (N-M) are used to represent the fractional portion (c) S. Thompson, M. Winters 25
Floating-Point Types For mathematical and scientific calculations Supports a wider range of values than integers approximations: range, precision determined by implementation equality representation: sign, exponent, mantissa real number = sign * mantissa * 2^exponent Example 32-bit float (a.k.a. Real) 1 bit sign 7 bits exponent (-64 to +63) Mantissa (.5 <= m < 1) double precision double in Java, C complex numbers pair of floats class definition (c) S. Thompson, M. Winters 26
Logical Types truth values often called Boolean representation bit vs byte literals C & C++ Book is incorrect. Both C & C++ support bool type. (as of 1999) Can use int in C for logical evaluation 0 = false, non-zero = true assignment vs equality test problem e.g. if(a=3) is always true! operations and, or, not short circuit (&&, ) (c) S. Thompson, M. Winters 27
Character Types operations relational and equality a < b < c Equivalent integer value coding scheme unspecified, e.g. Pascal ASCII, e.g. Ada Unicode, e.g. Java char in C 1 byte integer signed & unsigned compiler dependent wchar_t type (wide character) (c) S. Thompson, M. Winters 28
Character Types Unicode Originally was 16-bit (Java 1.0) Standard is at Unicode 5 UTF-8, UTF-16, UTF-32 Multi-byte representation Strings array of char, e.g. Pascal, C, Ada library class, e.g. Java built-in type, e.g. Perl, SNOBOL (c) S. Thompson, M. Winters 29
Enumeration Types User-defined types Used to improve readability named values mapped to integers but not integers e.g. days of the week Pascal: type Days = (Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday) C/C++: enum Days {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; operations relational operators Predecessor & successor Integer representation advantages with switch statements (c) S. Thompson, M. Winters 30
Enumerated Types unnamed enums used in C as a replacement for #define Classic enum trick in C++; overloading enumerands e.g. Ada type Light is (red, amber, green); type Flag is (red, white); not allowed in Pascal, C, C++ boolean (Pascal/Ada) and char(ada) as enumerated type (Pascal, Ada) type Boolean = { false, true } Displaying (and inputting) enumerated values Requires switches & string manipulation (In C) always required by the programmer (c) S. Thompson, M. Winters 31
Enumerated Types C# & Java (1.5 & up) treat enumerations as classes Going to and from String form is supported by defaulted (same in Ada) Is much more typesafe Before 1.5, Java could use the enum pattern to emulate integer based enums class Days { public static final int Sunday = 1; public static final int Monday = 2;. } Referencing enums is much cleaner in C#/Java Uses the enum name as a prefix (like a static class member) E.g. Day d = Days.Sunday; (c) S. Thompson, M. Winters 32
Enumerated Types (java) See Examples: JavaEnumExamples.java (c) S. Thompson, M. Winters 33
Reference Types The value of the variable of a reference type is a memory location The type of value pointed to is specified at declaration Allows for type checking e.g. C/C++ : int ci = 4; int* cipoint; C/C++ has the addressof operator(&) (@ in delphi) cipoint = &ci; ci reference 34 cipoint reference copy dereferencing operator (* in C/C++) x = *cipoint; (c) S. Thompson, M. Winters 34
Reference Types Arithmetic operation using pointers C, C++ - yes e.g. cipoint++; Pascal, Ada, Java - no Special representation to represent invalid address NULL (or null, or nil) low level programming Aliases Pointers & pointer arithmetic are why C/C++ dominate system programming When there are more than one way of referring to an object Considered bad (although.) From previous slide (*cipoint) = 27; changes the value of ci to 27 as well. Can make state change non-obvious or dangerous parameter passing danger (c) S. Thompson, M. Winters 35
Dynamic Variables Some languages with pointers restrict them to following operations to control their use Dereferencing Equality operators Assignment Cannot assign address of an existing integer, can only refer to a dynamically created variable Example: Pascal type Integerpt = ^Integer; declare pointer type itself var pipoint: Integerpt; declares pointer variables new(pipoint); use dynamic storage allocation to bind pipoint^ = 17; assign a value (using dereferencing) reference pipoint reference copy (c) S. Thompson, M. Winters 36
Dynamic Variables C C++ int *cipoint; cipoint = (int *) malloc(sizeof(int)); cipoint = new int(); *cipoint = 17; C++ vs Java C++: Stype* spoint = new Stype(); Java: Stype spoint = new Stype(); Stype s; explicit pointer variable declaration and explicit dereferencing operator C, Pascal - yes Java - no (c) S. Thompson, M. Winters 37
Aliasing of References (Pascal) var another: Integerpt; declare another ptr another := pipoint; reference 17 pipoint reference another reference copy (c) S. Thompson, M. Winters 38
Garbage Creation after new(pipoint) reference copy pipoint reference reference 17 another reference after new(another)? (c) S. Thompson, M. Winters 39
Garbage explicit deallocation dispose (Pascal), delete (C++) e.g. dispose(pipoint); knowing what to dispose memory leaks dangling reference Reference counting Cyclic issues Still prone to leaks garbage collection Java efficiency (c) S. Thompson, M. Winters 40