Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

What is a type?

CSE 504
 Set of values
 Together with a set of operations on these
values that possess certain properties

Types in Programming
Languages

1 CSE 307 Spring 2004 2


R. Sekar

Topics to be covered Simple Types


 Data types in modern languages  Predefined
• simple and compound types •int, float, double, etc in C
 Type declaration  All other types are constructed, starting from
 Type inference and type checking predefined (aka primitive) types
 Type equivalence, compatibility, conversion • Enumerated :
and coercion •enum colors {red, green, blue} in C
 Strongly/Weakly/Un-typed languages
 Static Vs Dynamic type checking
CSE 307 Spring 2004 3 CSE 307 Spring 2004 4
R. Sekar R. Sekar
Compound Types Cartesian Product
 Types contructed from other types using  Let I represent the integer type and R
type constructors represent real type.
• Cartesian product (*)  The cross product I x R is defined in the
• Function types () usual manner of product of sets, i.e.,
• Union types (U) I x R = { ( i, r) | i in I, r in R}
• Arrays
• Pointers
• Recursive types  Note that cartesian product operator is
neither commutative nor associative.

CSE 307 Spring 2004 5 CSE 307 Spring 2004 6


R. Sekar R. Sekar

Product Types (Contd.) Labeled Product types


 Products types correspond to "tuples" in SML.  In cartesian products, components of a tupes don’t have
 They are not supported in typical imperative names.
languages, except with labels. • Instead, they are identified by numbers.

 Type on previous slide denoted int*real in In labeled products each component of a tuple is given a
name.
SML.  Labeled products are also called records (a language-
- val v = (2,3.0); neutral term)
val v = (2,3.0) : int * real  struct is a term that is specific to C and C++
struct t { int a; float b; char * c;};
- type mytype = int * real; in C
type mytype = int * real

CSE 307 Spring 2004 7 CSE 307 Spring 2004 8


R. Sekar R. Sekar
Function Types Union types
 T1  T2 is a function type  Union types correspond to set unions, just like
• Type of a function that takes one argument of type T1 and product types corresponded to cartesian products.
returns type T2
 Standard ML supports functions as first class  Unions can be tagged (aka discriminated) or
values. untagged (undiscriminated). C/C++ support only
• They can be created and manipulated by other functions. untagged unions:
 In imperative languages such as C/C++, we can union v {
pass pointers to functions, but this does not offer int ival;
the same level of flexibility. float fval;
• E.g., no way for a C-function to dynamically create and char cval;
return a pointer to a function;
};
• rather, it can return a pointer to an EXISTING function

CSE 307 Spring 2004 9 CSE 307 Spring 2004 10


R. Sekar R. Sekar

Tagged Unions Array types


 In untagged unions, there is no way to ensure that the  Array construction is denoted by
component of the right type is always accessed.
• a rra y ( < ra n g e > , < e le m e m t Ty p e > ) .
• E.g., an integer value may be stored in the above union, but due to a
programming error, the fval field may be accessed at a later time.  C-declaration
• fval doesn’t contain a valid value now, so you get some garbage. int a[5];
 With tagged unions, the compiler can perform checks at defines a variable a of type a rra y(0 -4 , in t )

runtime to ensure that the right components are accessed.
Tagged unions are NOT supported in C/C++.
 A declaration
 Pascal supports tagged unions using VARIANT RECORDs
union tt b[6][7];
RECORD declares a variable b of type a rra y(0 -4 ,
CASE b: BOOLEAN OF a rra y(0 -6 , u n io n t t))
TRUE: i: INTEGER; |  We may not consider range as part of type
FALSE: r: REAL
END
CSE 307 Spring 2004 11 CSE 307 Spring 2004 12
END R. Sekar R. Sekar
Pointer types Polymorphism
 A pointer type will be denoted using the syntax  Ability of a function to take arguments of
p t r(< e le m e n tTyp e > ) multiple types.
where < e le m e n t Typ e > denote the types of the
object pointed by a pointer type.
 The primary use of polymorphism is code
 The C-declaration reuse.
char *s;  Functions that call polymorphic functions can
defines a variable s of type p tr(c h a r) use the same piece of code to operate on
 A declaration different types of data.
int (*f)(int s, float v)
defines a (function) pointer of type
p t r(in t*flo a t 
in t)
CSE 307 Spring 2004 13 CSE 307 Spring 2004 14
R. Sekar R. Sekar

Overloading (adhoc polymorphism) Polymorphism & Overloading


 Same function NAME used to represent different  Parametric polymorphism:
functions,
• implementations may be different • same function works for arguments of different types
• arguments may have different types • same code is reused for arguments of different types.
 Example:
• operator '+' is overloaded in most languages so that they
• allows reuse of "client" code (i.e., code that calls a
can be used to add integers or reals. polymorphic function) as well
• But implementation of integer addition differs from float  Overloading:
addition.
• Arguments for integer addition or ints, for float addition, they • due to differences in implementation of overloaded
are floats. functions, there is no code reuse in their
 Any function name can be overloaded in C++, but not in implementation
C. • but client code is reused
 All virtual functions are in fact overloaded functions.
CSE 307 Spring 2004 15 CSE 307 Spring 2004 16
R. Sekar R. Sekar
Code reuse with
Parametric polymorphism in C++ Parametric Polymorphism
template <class C>  With parametric ploymorphism, same
Type min(const Type* a, int size, Type minval) {
for (int i = 0; i < size; i++)
function body reused with different
if (a[i] < minval) datatypes.
minval = a[i];
return minval;
 Basic property:
} • does not need to "look below" a certain level
 Note: same code used for arrays of any type. • E.g., min function above did not need to look
• The only requirement is that the type support the "<" inside each array element.
and “=“ operations
 The above function is parameterized wrt class C • Similarly, one can think of length and
append functions that operate on linked lists of
• hence the term "parametric polymorphism". all types, without looking at element type.

CSE 307 Spring 2004 17 CSE 307 Spring 2004 18


R. Sekar R. Sekar

Code reuse with overloading Example


 No reuse of the overloaded function
• there is a different function body corresponding to each void
argument type. g(int size, C *a[]) {
 But client code that calls a overloaded function for (int i = 0; i < size; i++)
can be reused. a[i]->f(...);
 Example: }

• Let C be a class, with subclasses C1,...,Cn.  Now, the body of function g (which is a client of
• Let f be a virtual method of class C
the function f) can be reused for arrays that
• We can now write client code that can apply the contain objects of type C1 or C2 or ... or Cn,or
function f uniformly to elements of an array, each of
which is a pointer to an object of type C1,...,Cn. even a mixture of these types.
CSE 307 Spring 2004 19 CSE 307 Spring 2004 20
R. Sekar R. Sekar
Type Equivalence Type Equivalence (contd.)
 Structural equivalence: two types are  Structural equivalence is the least restrictive
equivalent if they are defined by identical type  Name equivalence is the most restrictive.
expressions.  Declaration equivalence is in between
• array ranges usually not considered as part of the type TYP E t 1 = ARRAY [ 1 . . 1 0 ] o f I N T EGER; V AR v 1 : ARRAY
• record labels are considered part of the type.
 Name equivalence: two types are equal if they
[ 1 . . 1 0 ] O F I N T EGER;

TYP E t 2 = t1; V AR v 3 , v 4 : t 1 ; V AR v 2 : ARRAY

[ 1 . . 1 0 ] O F I N T EGER;
have the same name.
 Declaration equivalence: two types are Structurally
equivalent?
Declaration
equivalent?
Name
equivalent?
equivalent if their declarations lead back to the t1, t2 Yes Yes No
same original type expression by a series of
v1, v2 Yes No No
redeclarations.
v3, v4 Yes Yes Yes
CSE 307 Spring 2004 21 CSE 307 Spring 2004 22
R. Sekar R. Sekar

Declaration equivalence: Type Compatibility


 In Pascal, Modula use decl equivalence  Weaker notion than type equivalence
 In C/C++  Notion of compatibility differs across operators
• Decl equiv used for structs, unions and classes
• Structual equivalence for other types.  Example: assignment operator:
struct { int a ; float b ; } x ; • v = expr is OK if <expr> is type-compatible with v.
struct { int a ; float b ; } y ; • If the type of expr is a Subtype of the type of v, then
 x and y are structure equivalent but not declaration there is compatibility.
equivalent.
typedef int* intp ;
 Other examples:
typedef int** intpp ; • In most languages, assigning integer value to a real
intpp v1 ; variable is permitted, since integer is a subtype of real.
intp *v2 ; • In OO-languages such as Java, an object of a derived
 v1 and v2 are structure equivalent. type can be assigned to an object of the base type.
CSE 307 Spring 2004 23 CSE 307 Spring 2004 24
R. Sekar R. Sekar
Type Compatibility (Contd.) Type Checking
 Procedure parameter passing uses the  Static (compile time)
same notion of compatibility as assignment • Benefits
• Note: procedure call is a 2-step process • no run-time overhead
• assignment of actual parameter expressions to the • programs safer/more robust
formal parameters of the procedure  Dynamic (run-time)
• execution of the procedure body • Disadvantages
 Formal parameters are the parameter names • runtime overhead for maintaining type info at runtime
that appear in the function declaration. • performing type checks at runtime
 Actual parameters are the expressions that • Benefits
appear at the point of function call. • more flexible/more expressive
CSE 307 Spring 2004 25 CSE 307 Spring 2004 26
R. Sekar R. Sekar

Examples of Static and


Dynamic Type Checking Strong Vs Weak Typing
 C++ allows  Strongly typed language: such languages will
execute without producing uncaught type errors
• casting of subclass to superclass (always type- at runtime.
safe) • no invalid memory access
• superclass to subclass (not necessarily type-safe) • no seg fault
– but no way to check since C++ is statically typed. • array index out of range
 Java uses combination of static and dynamic •
• access of null pointer
No invalid type casts
type-checking to catch unsafe casts (and  Weakly typed: uncaught type errors can lead to
array accesses) at runtime. undefined behavior at runtime
 In practice, these terms used in a relative sense
 Strong typing does not imply static typing
CSE 307 Spring 2004 27 CSE 307 Spring 2004 28
R. Sekar R. Sekar
Type Checking (Contd.) Type Checking (Contd.)
 Type checking relies on type compatibility and type  In SML, type inference rules capture bottom-up
inference rules. as well as top-down flow of type info.
 Type inference rules are used to infer types of
Example of Top-down:
expressions. e.g., type of (a+b)+c is inferred from type of
a, b and c and the inference rule for operator ‘+’. fun f x y = (x+y): real
 Type inference rules typically operate on a bottom-up f:real
fashion.
Example: (a+b)+c +:real
x:real y:real
+:real c:real  Here types of x and y inferred from return type of f (real).
Note: Most of the time SML programs don't require type
declaration.
a:int b:real
CSE 307 Spring 2004 29 CSE 307 Spring 2004 30
R. Sekar R. Sekar

Type Conversion Data Types Summary


 Explicit: Functions are used to perform  Simple/built-in types
conversion.  Compound types
example: strtol, atoi, itoa in C; real and int etc. • Product, union, recursive, array, pointer
 Implicit conversion (coercion)  Type expressions
 Types in SML
example:
• If a is real and b is int then type of a+b is real  Parametric Vs subtype polymorphism, Code
• Before doing the addition, b must be converted to a real value. reuse
This conversion is done automatically.  Polymorphism in SML, C++, Java
 Casting (as in C)  Type equivalence
 Invisible “conversion:” in untagged unions • Name, structure and declaration equivalence
 Type compatibility
 Type inference, type-checking, type-coercion
CSE 307 Spring 2004 31
 Strong Vs Weak, Static Vs Dynamic typing
CSE 307 Spring 2004 32
R. Sekar R. Sekar

You might also like