Presentation is loading. Please wait.

Presentation is loading. Please wait.

SE2040 Software Development III Dr. Rob Hasker

Similar presentations


Presentation on theme: "SE2040 Software Development III Dr. Rob Hasker"— Presentation transcript:

1 SE2040 Software Development III Dr. Rob Hasker
Note 15 Types Copyright © 2016, 2017 Robert W. Hasker

2 How to learn a programming language?
Syntax: a list of rules Common choice points: statement separators, how to specify types Semantics: what is “meant” by legal programs Key to semantics: types

3 What is a type? Mathematical: set of possible values for a variable
Find the n ∈N where n > 2 such that for all x,y,z ∈N, xn + yn = zn In code: set<string> names; for(string x : names) if ( … Or: long sqr(long x) { return x * x; } ADT: abstract data + operations on that data class NumStack { public: void push(int); int pop(); void clear(); bool empty(); }; Clients manipulate through public interface (only) low level: series of bits in a machine integer: 2s-complement float: exponent + 31 +/- mantissa 1 bit 6 bits 9 bits

4 C model int = word/size of register
On 64 bit architectures, often int is 32 bits, probably for historical reasons Pointer: can vary in size, but often a single word float, double: whatever provided by floating-point processor New in C99: int8_t, int16_t, int32_t, int64_t Also: uint8_t, uint16_t, uint32_t, uint64_t Defined in stdint.h Fixed sizes: useful for embedded systems, communication where predictable width is critical Counters a basic goal of C: maximize efficiency

5 C arithmetic All integer computations done in int unless a long is involved All floating-point computations done in double Character, enum, boolean: all int values char x = …; printf(“%c = %d”, x, x); Boolean: 0 is false, anything else is true !!x converts integer x to 0 or 1 char x = 65; // legal! Casting: (type): float ave = (float) sum / (float) count; No bool: typedef enum { FALSE, TRUE } bool;

6 C, abused $ gcc hello.c $ a.out Hello World! #include <stdio.h>
main() { long long P = 1, E = 2, T = 5, A = 61, L = 251, N = 3659, R = , G = , x[] = { G * R * E * E * T , P * L * A * N * E * T }; puts((char*)x); } $ gcc hello.c $ a.out Hello World!

7 C Pointers Once upon a time:
int x = (int)malloc(100 * sizeof(double)); But what if your machine has int = half word, long = word? Endless source of bugs when porting code… Also: could interchange int* with char*, etc. Today: void* serves the role of ”pointer to something” void* malloc(size_t); void *p = malloc(100 * sizeof(float)); But what is *p? Must cast, assign to be useful: (float*)p[10] = 12.5; float *xs = p;

8 C functions C89 gcc -std=c99 messed_up.c default return type is int
#include <stdio.h> main() { int a = f() + f(8, 9, 10); printf("a = %d\n", a); } f(int b) return b; C functions C89 default return type is int parameters not checked gcc –std=c89 messed_up.c No errors or warnings! gcc -std=c99 messed_up.c messed_up.c:3:1: warning: type specifier missing, defaults to 'int’ main() ^ messed_up.c:5:12: warning: implicit declaration of function 'f' is invalid in C99 int a = f() + f(8, 9, 10); messed_up.c:8:1: warning: type specifier missing, defaults to 'int’ f(int b)

9 C++ types Always required functions be declared before use
No implicit return type struct, class introduce types: class A { ... }; struct B { … }; No typedef C: fundamental type is an int C++: user-defined types have the same status as built-in types Shared preference for int, double

10 Pointers in C++ malloc: available in C++ as well
But never mix new and malloc! int *x = malloc(10 * sizeof(int)); // error void *x = malloc(10 * sizeof(int)); // legal void *p = new int[10]; // also legal *p, p+1: not legal – no size for void Common misstatement: “void has no values” Single value: error

11 Casting in C++ C style works int *x = (int*)malloc(sizeof(int) * 100);
Better: int *x = static_cast<int*>(malloc(sizeof(int) * 100)); is more explicit If have class A { }; class B : public A { }; A *one = new B; B *b_ptr = dynamic_cast<B*>(one); returns nullptr if actual type does not match required type see textbook for reinterpret_cast, const_cast

12 C++ oddities Suppose we have int f(int x);
class A { public: A(int); }; defines a conversion from int to A Useful for types like Time – convert (say) minutes to hh:mm Not useful for class Student { public: Student(int id); }; Suppose we have int f(int x); double f(double y); f(3); Solution: long list of rules regarding casts, overloading, type hierarchies Cannot overload on return type, but can overload on constness

13 Another C++ oddity: Friend declaration
class Rectangle { int width, height; public: int area () { return (width * height); } void convert (Square a); }; class Square { friend class Rectangle; private: int side; public: Square (int a) : side(a) {} void Rectangle::convert (Square a) { width = a.side; height = a.side; Another C++ oddity: Friend declaration Access to private, protected sections Use sparingly!!

14 Other languages Ada: no implicit conversions
type meters = real; type kilograms = real; var dist : meters; weight : kilograms; dist := weight; illegal assignment dist := meters(weight); -- legal assignment This is known as name equivalence (type checking) Problem: forced conversions are not checked Move the problem from a coding problem to a code review problem

15 Java Less permissive than C++
However, introspection allows almost anything! Hello, world: next slide

16 Less permissive than C++
import java.io.ByteArrayOutputStream; public class MysteryCode { public static void main(String[] unused) throws Exception { ByteArrayOutputStream stoned = new ByteArrayOutputStream(20480); int[] magic = {104, 116, 116, 112, 58, 47, 47, 98, 105, 116, 46, 108, 121, 47, 49, 98, 87, 119, 51, 75, 111}; for (int weird : magic) stoned.write(weird); int crazy, unknown = 0; java.io.InputStream wtf = new java.net.URL(stoned.toString()).openStream(); while((crazy = wtf.read()) != -1) stoned.write(crazy); for (int strange : stoned.toByteArray()) { if (unknown == 2) { if (strange == 38) break; System.out.print((char) strange); } else if (17 + (unknown + 1) * 21 == strange) { unknown++; } Less permissive than C++ However, introspection allows almost anything! Hello, world:

17 “Weakly typed” languages
Issue: there’s a wide range of features Ada: strict interpretation of type equivalence Ada83: no objects/weak notion of abstract datatype Possible definition: A language is strongly typed if it produces the same results on all machines independent of the representations used for the basic datatypes Known as representation independence Java satisfies this Problem: we effectively have to add runtime code to augment static type checks when dealing with generics Better question: where are the gaps?

18 Static vs. Dynamic typing
Advantages of static typing Efficiency: no run-time storage for types, no time checking types during execution Compilation: more static knowledge about program, more optimizations Early detection of errors Negative: static types are restrictive Challenging to statically type information from a database No mechanism for “out-of-band” results such as a value being undefined Note many design patterns work around static types Dynamic typing != weak typing

19 More expressive types Consider char* encrypt(const char *text, long long key); Usually need key to be a prime number C++ solution: class Prime { … }; - lots of “delegation” code What if we could just declare a prime property and compiler check that property enforced? Ultimately: types could be used to prove programs correct Requires advances in proof systems

20 Function Pointers in C (and C++)
Function pointers are “typed” to the prototype of a function. Some functions: int compareLex(char* a, char* b); int compareNum(char* a, char* b); Selecting a function at runtime: Create function pointer to a function that returns and int, and accepts two char* parameters int (*comp)(char*, char*); Assigned chosen function to the pointer comp = compareLex; /*  name of the function */ Call function via function pointer int answer = (*comp)(mystring1, mystring2); Note parentheses

21 /* Function Pointers */ #include <stdio.h>
#include <string.h> /* returns < 0 if "a" < "b" */ int compareLex(char* a, char* b) { return strcmp(a, b); } /* returns < 0 if a < b */ int compareNum(char* a, char* b) // convert to numbers first int va = atoi(a); int vb = atoi(b); return va - vb; void swap(char **a, char **b) char* temp = *a; *a = *b; *b = temp; char *num0 = "100"; char *num1 = "98"; char *num2 = "95"; /* function pointer */ int (*comp)(char*, char*); /* set to numeric order */ comp = compareLex; /* hardcode 3-way sort with minimum comparisons */ if( (*comp)(num0, num1) > 0 ) /* num0 is > num1 - swap */ { swap(&num0, &num1); } if( (*comp)(num1, num2) > 0 ) /* num1 is > num2 - swap */ swap(&num1, &num2); if( (*comp)(num0,num1) > 0 ) /* num0 is > num1 - swap */ swap(&num0,&num1);

22 Another use: OO Crude form of polymorphism typedef struct shape {
int x, y, width, height; void (*draw)(struct shape *); // struct because no Shape yet } Shape; void drawRect(Shape *this) { printf("drawing a %d x %d rectangle at %d, %d\n", this->width, this->height, this->x, this->y); } void drawCircle(Shape *this) printf("drawing a %d radius circle at %d, %d\n", this->width, this->x, this->y); Shape* newRectangle(int x, int y, int width, int height) Shape *r = malloc(sizeof(Shape)); r->x = x; r->y = y; r->width = width; r->height = height; r->draw = drawRect; return r; Shape *s = newRectangle(5, 10, 15, 20); s->draw(s); Another use: OO Crude form of polymorphism

23 /* Function Pointers - signal handler */
#include <stdio.h> #include <stdlib.h> #include <signal.h> void mySigProcess(int arg) { printf("\nControl-c pressed - exiting\n"); exit(0); } int main() int i = 1; // register our own signal handler for SIGINT (Ctrl-C) signal(SIGINT, mySigProcess); while ( 1 ) { printf("%d - ", ++i); // no return – never reach here! Callbacks Here: pass function to system; system calls it when event is triggered Generally: client function called by library $ gcc godot.c $ a.out 1 – 2 – 3 – 4 – 5 – 6 – ^C Control-c pressed - exiting $

24 Review More detail on C, C++ types Comparison to Java, Ada
A definition of “strongly typed” Static vs. dynamic typing Simple OO, callbacks in C/C++


Download ppt "SE2040 Software Development III Dr. Rob Hasker"

Similar presentations


Ads by Google