Chapter 5 Data Types SANGJI University KO Kwangman ([email protected])

71
Chapter 5 Data Types SANGJI University KO Kwangman ([email protected])

Transcript of Chapter 5 Data Types SANGJI University KO Kwangman ([email protected])

Page 1: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

Chapter 5Data Types

SANGJI University

KO Kwangman([email protected])

Page 2: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

2

1. Introduction Type supports abstraction

RealWorld

NaturalNumbers

RealNumbers

ProgrammingLanguage

int

data

double

data

ProgrammingLanguage

Implementation

binary digitsin sizeof(int)

bytes

binary digitsin sizeof(int)

bytes

유한성 (finite)추상화 (abstraction)

concreterepresentation

2'scomplement

IEEE754

Chap. 5 : Data Type

Page 3: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

타입 (type)~ 값의 집합과 그 값들에 대한 연산의 집합 . ~ 정수 타입

값 : ..., -2, -1, 0, 1, 2, ... 연산 : +, -, *, /, <, ... 로 구성

~ 불 타입 값 : true, false

연산 : , ,

Chap. 5 : Data Type 3

Page 4: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

5.1 자료형 오류 컴퓨터에 저장된 데이터

~ 자료형 정보를 가지고 있지 않다 . ~ 기본적으로 비트들의 열 (sequence) 을 저장

예 : 0100 0000 0101 1000 0000 0000 0000 0000

비트열의 가능한 해석~ 부동 소수점 수 3.375• 32 비트 정수 1,079,508,992. • 두 개의 16 비트 정수 16472 와 0 • 네 개의 ASCII 문자열 @ X NUL NUL

Chap. 5 : Data Type 4

Page 5: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

타입 오류 (type error) ~ 어떤 연산을 해당하지 않는 타입의 값에 적용함으로써

발생하는 오류 ~ 어셈블리 프로그램 작성 시에 자주 발생 ~ 고급 언어의 경우에는 컴파일러와 실행시간 시스템이 타입

오류를 검사 및 추출 ~ 타입 체계 (type system) 는 타입 오류를 검출하기 위한

기반을 제공

Chap. 5 : Data Type 5

Page 6: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

5.2 정적 및 동적 타입 결정 타입 체계

~ 덧셈에 사용되는 값은 숫자여야 한다는 것과 같은 제약을 보장

~ EBNF 를 사용하여 문법적으로 표현할 수 없음 .

자료형 검사~ 컴파일 시간에 타입 검사 수행

C 언어~ 실행 시간에 타입 검사 수행

Perl 언어~ 두 가지 방법을 다 사용하기도 한다 .

Java 언어

Chap. 5 : Data Type 6

Page 7: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

statically typed~ 변수의 타입이 컴파일 시간에 선언에 의하여 고정~ 정적으로 타입이 결정 (statically typed) 되는 언어

dynamically typed~ 변수의 타입이 저장되는 값에 따라 실행 중에 볂하~ 동적으로 타입이 결정 (dynamically typed ) 되는 언어

Chap. 5 : Data Type 7

Page 8: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

strongly typed 언어~ 타입 체계가 컴파일 중이나 실행 중에 모든 타입 오류를

찾아낼 수 있을 언어~ 동적 타입 결정 또는 정적 타입 결정 . ~ 유니온 (union) 타입

많은 언어들에서 타입 체계의 허점의 원인 ~ 동적으로 타입이 결정되는 언어는 각각의 값에 타입을 함께

저장

Chap. 5 : Data Type 8

Page 9: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

5.3 기본 타입 현재 32-bit 컴퓨터에서 사용되는 용어

~ Nibble: 4 bits~ Byte: 8 bits~ Half-word: 16 bits~ Word: 32 bits~ Double word: 64 bits~ Quad word: 128 bits

대부분의 언어에서 숫자 타입은 유한한 크기~ a + b, Overflow 가능성~ 수학과의 차이점 존재 :

a + (b + c) (a + b) + c

Page 10: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

중복 (overloaded)

~ 함수나 연산자가 인수의 타입에 따라 그 의미가 달라지는 것~ a + b in Java

정수 덧셈 부동소수점수 덧셈 문자열 접합 (concatenation)

~ 혼합모드 하나는 정수이고 다른 인수는 부동소수점수인 경우

Page 11: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

자료형 변환~ narrowing 변환

원래 값보다 더 적은 수의 비트열을 결과로 생성하는 타입 변환

~ widening~ 묵시적 변환이 허용되지 않는 이유 ?

Chap. 5 : Data Type 11

Page 12: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

5.4 사용자 정의 자료형 열거형 (Enumeration) :

enum day {Mon, Tue, Wed, Thu, Fri, Sat, Sun};enum day myDay = Wednesday;

~ C/C++ 에서 위 타입들의 값은 0, ..., 6 이 사용된다 .~ Java 는 더 강력한 구조가 사용

for (day d : day.values()) Sytem.out.println(d);

Chap. 5 : Data Type 12

Page 13: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

Pointer 포인터 (pointer)

~ 다른 변수의 주소를 가지고 있는 변수

~ 포인터가 가리키는 내용의 변경 : * 연산자 사용

Chap. 5 : Data Type 13

char a='A';char *p;p = &a;

26

‘A’

변수 a

주소

26

포인터 p

*p= 'B';

Page 14: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

포인터 연산자~ & 연산자

변수의 주소를 추출~ * 연산자

포인터가 가리키는 곳의 내용을 추출

Chap. 5 : Data Type 14

26

‘A’

변수 a

주소

26

포인터 p

&a*p

Page 15: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

포인터의 사용

struct Node {int key;struct Node* next;

};struct Node* head;

Chap. 5 : Data Type 15

Page 16: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

포인터 사용에서 발생될 수 있는 문제~ 신뢰성 있는 소프트웨어의 개발을 방해 . ~ 오류가 생기기 쉽다~ 버퍼 넘침 (Buffer overflow), 메모리 누출 (memory

leaks)~ 특히 C 에서 문제가 많이 발생함

Chap. 5 : Data Type 16

Page 17: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

Array, List 배열 (array)

~ 동일 자료형 (same type) 의 자료들이 순서 (linear) 있게 구성된 집합

~ 연속된 기억 공간 차지~ 유한한 개수의 자료가 저장됨~ 직접접근 (direct access)

기준위치에 대한 상대적 위치를 나타내는 인덱스 (index)를 사용하여 가능

Chap. 5 : Data Type 17

… … A[0] A[1] A[9]

시작주소 (base)

배열이름 : 기억장소의 시작위치 ( 주소 )

인덱스 ( 첨자 )

Page 18: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

Java 에서의 배열~ 선언 (declaration)

생성될 배열 시작 위치 저장 int dsInt [] ;

~ 생성 (creation) 힙 메모리에서 배열 크기만큼의 기억 공간을 할당한 후 시작 주소를 배정

dsInt = new int[3] ;

Chap. 5 : Data Type 18

1) int dsint []

2) dsInt = new int[3]

dsInt[0]

dsInt[1]

dsInt[2]

3) 생성된 배열의시작주소 전달

Page 19: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

Homeworks~ 연결 리스트~ 구조체~ 유니온~ 문자열~ 부분 범위형

Chap. 5 : Data Type 19

Page 20: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

20

명시적 자료형 (Explicit Typing) 정적 자료형 검사 (static type checking)

~ static type checking is still controversial.~ 유연성 (flexibility)

자료형 결정 및 검사를 느슨 또는 반대~ 신뢰성 (reliability) 또는 보안 (security)

최대한 제약성 (restrictiveness) 엄격한 번역 시간 자료형 검사

Flexibility

type-lesslanguage

Reliability(security)

strongly typedlanguage

stillcontroversial

Chap. 5 : Data Type

Page 21: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

21

정적 자료형 검사의 이유1. 수행 효율성 (execution efficiency)

~ no need to run-time type checking~ 효율적인 메모리 할당~ 효율적인 목적기계 코드 생성

2. 번역 효율성 (Translation Efficiency)~ 분리 컴파일 (separate compilation) 가능~ 재컴파일시 컴파일되는 코드의 양을 줄일 수 있음

3. 작성 용이성 (writability, Coding Efficiency)~ 번역시에 타입 에러를 조기에 발견

Chap. 5 : Data Type

Page 22: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

22

4. 보안과 신뢰성 (security & reliability)~ 실행시 발생 될 수 있는 에러를 사전 차단

5. 판독성 (readability)~ 명시적 자료형 선언은 자료형 설계를 문서화~ good for documentation

6. 모호성 제거 (remove ambiguity)~ 다중 적재된 명칭 (overloaded names) 에 대한 모호성

해결 (resolving)

7. …

Chap. 5 : Data Type

Page 23: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

23

자료형 정의 정의 _1

~ a set of values~ ex) the data type int in Java

~ Vint = { x | x ∈ Z, ~ -2,147,483,648 ≤ x ≤ 2,147,483,647 }

정의 _2~ a set of values with a set of operations~ ex) the data type int in Java

Vint = { x | x ∈ Z, -2,147,483,648 ≤ x ≤ 2,147,483,647 }

with the following set of operationsFint = { +, -, *, … }

Chap. 5 : Data Type

Page 24: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

24

자료형 검사 , 자료형 추론 자료형 검사 (type checking)

~ 번역기가 프로그램내에 자료형 정보에 문제가 없는지 검사한 과정

~ 연산자 ( 서브 프로그램 ) 과 피연산자 ( 매개변수 ) 사이에 자료형의 일관성 (type consistency) 을 검사한 과정

자료형 추론 (type inference)~ 수식에 자료형 부착 (attaching) 시키는 동작~ z=x/y 에서 z 의 자료형을 결정하기 위해서 ?

x, y 의 의 자료형이 결정되어야 함 .

상호의존족~ 자료형 검사와 자료형 추론은 상호의존적

Chap. 5 : Data Type

Page 25: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

25

Constructing Types 자료형 구성자 (type constructors)

~ 기본 자료형으로 부터 새로운 자료형을 구성~ Derived types are parameterized type constructors.

Basic Types(primitive types)

int, double, …

Derived Typesarray, structures,

…type constructors

type constructors

사용자 - 정의 자료형(user-defined data type)

Chap. 5 : Data Type

Page 26: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

26

자료형 선언 (type declaration)~ 새로운 자료형에 이름 부여

(In C example)

typedef int int10[10];

Chap. 5 : Data Type

Page 27: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

27

자료형 시스템 (type system) 자료형 동등성 (type equivalence) 알고리즘

~ 두 개의 자료형이 일치하는지 여부를 결정하는 알고리즘~ 방법 ?

자료형 시스템 (type system)~ 자료형 구성 방법~ 자료형 동등성 알고리즘~ 자료형 검사 , 자료형 추론~ …

Chap. 5 : Data Type

Page 28: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

28

Typing 엄격한 자료형 (strongly-typed) 언어

~ 모든 자료형 에러가 번역 시간에 발견~ 가능한 가장 이른 시점에 프로그램내의 모든 에러 발견~ 예외 (exception) 검사

실행 도중에만 검사할 수 있는 오류 s.~ 불안전한 프로그램은 대부분 번역 시간에 거부~ 너무 엄격해서 적법한 프로그램까지 거부~ 적적한 자료형 정보를 프로그래머가 명시적으로 제공

~ Ada, Haskell, Pascal, …

Chap. 5 : Data Type

Page 29: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

29

느스한 자료형 (weakly-typed) 언어~ the languages which detect type errors during

translation time but allow a few loopholes

타입 결여 (untyped) 언어~ 정적 자료형 시스템을 지원하지 않는 언어~ 데이터 안전성에 관한 검사가 실행시간에 이루어짐 .~ Scheme, LISP, Smalltalk, Perl, …

Chap. 5 : Data Type

Page 30: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

30

Safe Programs

Every well-typed programs are safe but not vice versa.

Executable Programs

Legal Programs(Safe Programs)

Well-Typed Programs

Unsafe Programs

contain data-

corrupting errors

Chap. 5 : Data Type

Page 31: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

31

단순 타입 (Simple Types)

단순 타입~ atomic types~ the types which contain no other type substructures

단순 타입의 분류

SimpleTypes

Predefined Simple Types

User-Defined Ordinal Types

Enumeration Types

Subrange TypesDefined

Operators: • successor• predecessor• comparison

Chap. 5 : Data Type

Page 32: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

32

Ordinal Type Example Enumerated Type in C

enum Color { Red, Green, Blue };

Enumerated Type in Adatype Color_Type is (Red, Green, Blue);

Enumerated Type in MLdatatype Color_Type = Red | Green | Blue;

Java does not have enumerated types.

Subrange Type in Adatype Digit_Type is range 0..9;

Chap. 5 : Data Type

Page 33: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

33

Some Notes on Simple Types 순서 타입 (ordinal type)

~ 비교 연산자를 항상 지원하지 않음~ ex) Subrange of floating-point numbers in Ada.

type Unit_Interval is range 0.0..1.0;

부분범위타입 (subrange type)

type Digit_Type is range 0 .. 9;

~ 효과 ?

단순 자료형은 하드웨어상에서 직접 구현~ 하드웨어 효율성 중시

Chap. 5 : Data Type

Page 34: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

34

Type Constructors 타입

~ 집합 (set) ~ 집합 연산이 기존의 타입에서 새로운 타입을 구성하는데

사용

타입 구성자 (type constructor)~ 집합 연산이 타입에 적용~ 데카르트 곱 , 합집합 , 멱집합 , 함수집합 , 부분집합 .

Chap. 5 : Data Type

Page 35: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

35

데카르트 곱 (cartesian product) Cartesian product

~ a set of pairs~ 두 집합 U, V 에 대한 모든 원소들의 순서쌍 (ordered pair)

U ⅹ V = { (u, v) | u∈ U and v ∈ V }

with projection functions p1 and p2:

p1: U ⅹ V → U p1 ((u, v)) = u

p2: U ⅹ V → V p2 ((u, v)) = v

corresponding to the Cartesian products~ record (structure) constructors

Chap. 5 : Data Type

Page 36: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

36

Example: Structure Types in Cstruct IntReal // IntReal = int doubleⅹ{ int i; double r;};struct IntReal x = {1, 2.5}; // x = (1, 2.5) IntReal∈

x.i // p1(x)

x.r // p2(x)component selector operation(structure member operation)

Chap. 5 : Data Type

Page 37: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

37

합집합 (union) 합집합 종류

~ 비구별 합집합 (undiscriminated union) normal set union

~ 구별 합집합 (discriminated union) 원소를 구별하기 위한 태그 (tag) 가 첨부

Chap. 5 : Data Type

Page 38: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

38

Example: Union in C~ undiscriminated union: a union itself~ discriminated union: a union embedded in a

structure

union IntOrReal{ int i; double r;};

enum Disc {IsInt,IsReal};struct IntOrReal{ enum Disc which; union { int i; double r; } val;};

Chap. 5 : Data Type

Page 39: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

39

More Safe Union

Variant Records in Ada~ the discriminant and the

value should be assigned at once

Datatype in ML~ enumerators may

include data fields~ pattern matching using

case expressions

type Disc is (IsInt, IsReal); type IntOrReal (which: Disc) is record   case which is     when IsInt =>  i:integer;    when IsReal => r:float;   end case; end record; ... x: IntOrReal := (IsReal,2.3);

datatype IntOrReal = IsInt of int | IsReal of real; ... fun printIntOrReal x =   case x of     IsInt(i) => printInt i |     IsReal(r) =>printReal r ;

Page 40: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

40

부분집합 (subset) 부분집합

~ supported by subtypes( 부분자료형 ).

In Ada~ subtypes and subrange types are different:~ subtype

subtype IntDigit_Type is integer range 0..9; ~ new type (that is a subrange of an existing type)

type Digit_Type is range 0..9;~ fixing the variant part of a variant record type

subtype IRInt is IntOrReal(IsInt);subtype IRReal is IntOrReal(IsReal);

Chap. 5 : Data Type

Page 41: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

41

Arrays and Functions Consider a function

f: U → V

If U is an ordinal type, f corresponds to an array:

U: index type, V: component typef(i) ∈ V which i ∈ U

Array Size Problem~ the size of an array may be or may not be the part of

an array

Chap. 5 : Data Type

Page 42: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

42

Array Example: C/C++ The size of an array is not part of the array.

~ When passing array parameters, the sizes of the arrays may have to be passed as separate parameters.int array_max (int a[], int size);

~ In a formal parameter, the array notation = pointer.

Difference between C and C++.~ 교재가 틀렸다 .

const int Size = 5;int x[Size]; /* illegal C, ok in C++ */int x[Size*Size]; /* illegal C, ok in C++ */

Chap. 5 : Data Type

Page 43: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

43

Array Example: Java, Ada

In Java,~ the size of an array is

the part of the array~ array can be

dynamically allocated

Unconstrained Array in Ada~ dynamically sized array~ 배열 선언시 크기 결정

// a part of Figure 6.3...int [] x = new int[u] ; // Dynamic array allocationfor (int i = 0; i < x.length;

i++) x[i] = i;...

type IntToInt is array (INTEGER range <>) of INTEGER;...declare x: IntToInt(1..size);begin for i in x'range loop x(i) := i;

Page 44: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

44

Multidimensional Array Supporting Multidimensional Array

~ Multidimensional array may be simulated by arrays of arrays (C, C++, Java)

기억 장소 할당 (memory allocation)~ Row-Major : natural way for arrays of arrays~ Column-Major : FORTRAN~ 특정 원소 접근 공식 ?

1 2 3

4 5 6

Row-Major: 1 3 5

2 4 6

Column-Major:

Chap. 5 : Data Type

Page 45: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

45

Passing Multidimensional Array 배열을 매개변수로 전달

~ 배열의 크기가 배열의 일부로 간주 there is no problem of array parameters.

~ 배열의 크기가 배열의 일부로 간주되지 않는 경우 매개변수 전달시 배열의 크기를 전달

passing 2-dimensional array in C/C++.~ When the both dimensions are known~ When the 1st dimension should be passed~ When the both dimensions should be passed

Chap. 5 : Data Type

Page 46: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

46

Passing no Dimensions#include <iostream>using namespace std;

const int R = 3, C = 3;

int sum(int a[R][C]){ int sum = 0; for (int i = 0; i < R; ++i) for (int j = 0; j < C; ++j) sum += a[i][j]; return sum;}

main(){ int a[R][C] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; cout << "1+2+..+9 = " << sum(a) << endl;}

Chap. 5 : Data Type

Page 47: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

47

Passing the 1st Dimension#include <iostream>using namespace std;

const int R = 3, C = 3;

int sum(int a[][C], int row){ int sum = 0; for (int i = 0; i < row; ++i) for (int j = 0; j < C; ++j) sum += a[i][j]; return sum;}

main(){ int a[R][C] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; cout << "1+2+..+9 = " << sum(a, R) << endl;}

Chap. 5 : Data Type

Page 48: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

48

Passing the Both Dimensions#include <iostream>using namespace std;

int sum(int a[], int row, int col){ int sum = 0; for (int i = 0; i < row; ++i) for (int j = 0; j < col; ++j) sum += a[i*col+j]; return sum;}

const int R = 3, C = 3;

main(){ int a[R][C] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; cout << "1+2+..+9 = " << sum(&(a[0][0]), R, C) << endl;}

Chap. 5 : Data Type

Page 49: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

49

Some Notes on 2-Dimensional Array Equivalences and Differences

~ for a constant Nint a[N] ≡ int a[] ≡ int *a

~ for constants M and Nint a[M][N] ≡ int a[][N] ≡ int (*a)[N]

~ beware thatint a[][N] ≠ int **a

Declarations of C/C++~ declarations implies the usages

int *a[N];int (*a)[N];

Chap. 5 : Data Type

Page 50: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

50

Pointer(Reference) Types Pointer(Reference) Type

~ 집합 연산에 대응되지 않는 타입 구성자~ 지정된 자료형을 지칭 ( 참조 ) 하는 모든 주소들의 집합~ 자동 쓰레기 수집에 허용되는 언어에서 포인턴 묵시적

Java, ML, Scheme

참조 vs. 포인터~ 참조 : 시스템 제어하에 있는 객체의 주소

값으로 사용 및 연산이 가해질 수 없음 .~ 포인터

값으로 사용 및 연산이 가해질 수 있음 .

double r = 2.3, &s = r;

Chap. 5 : Data Type

Page 51: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

51

In C and C++, arrays are constant pointers

int a[] = {1,2,3,4,5};

int* p = a; printf(“%d \n”, *p); printf(“%d \n”, *(p+2) ); printf(“%d \n”, *(a+2) ); printf(“%d \n”, 2[a]);

a[2] ≡ *(a + 2) ≡ 2[a] // Wow!

Chap. 5 : Data Type

Page 52: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

52

Recursive Types 순환 타입 (recursive types)

~ a type that uses itself in its declaration~ pointers are useful for recursive types

The Size Problem of Recursive Types~ require that the maximum size of a data type should

be determined at translation time.

Chap. 5 : Data Type

Page 53: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

53

struct CharList{ char data; struct CharList next;}; /* illegal! */

union CharList {  enum { nothing } empty;    struct    { char data;      union CharList next;    } charListNode; }; /* still, illegal! */

struct CharListNode { char data;   struct CharListNode* next;};

typedef struct CharListNode* CharList; /* Now, legal */

Page 54: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

54

Data Types and the Environment

Fully DynamicEnvironment

Recursive TypesGeneral Function

Types

Functional Languages

Traditional Environment

(stack & heap)

Recursive types and function types are implemented by

pointers

Algol-style Languages

Page 55: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

55

The Type Structure of C

Chap. 5 : Data Type

Page 56: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

56

The Type Structure of Java

Chap. 5 : Data Type

Page 57: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

57

Simplified Type Structure of Ada

Chap. 5 : Data Type

Page 58: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

58

타입 동등성 (Type Equivalence) 타입 동등성이란 ?

~ 두개의 타입이 어느때 같은 (= 일치 = 동등 ) 한가 !~ 종류

구조적 동치 (structural equivalence) 이름 동치 (name equivalence) 선언 동치 (declaration equivalence)

구조적 동치~ 두개의 타입이 동일한 구조 (same structure)~ 동일한 구조

the same type constructor and the same component types.

~ 교재 PP.258

Chap. 5 : Data Type

Page 59: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

59

이름 동치~ 두 개의 타입은 공일한 이름을 가질 때에만 동등

Declaration Equivalence~ Two types are equivalent if they are derived from the

same name.

Chap. 5 : Data Type

Page 60: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

60

Complicating Factors

Array Size~ 배열의 크기를 배열의 한 부분으로 간주 ?

Field Names of Record Types~ The following RecA and RecB should be structurally

equivalent (char ⅹ int) but not in practice because of the field names.

struct RecA{ char x; int y;};

struct RecB{ char a; int b;};

Chap. 5 : Data Type

Page 61: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

61

Language Example: Ada Ada

~ pure name equivalence the variables a and b in

a, b: array (1..10) of integer;are not type equivalent because the above declaration is considered as a shorthand fora: array (1..10) of integer;b: array (1..10) of integer;

~ the new types and the subtypes are different each other

new typetype Age is new integer;

subtype: compatible to the original typesubtype Age is integer;

Chap. 5 : Data Type

Page 62: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

62

Language Examples: Others Pascal

~ every type constructors introduce a new type~ new type names for existing type names are

equivalent

Java~ no ‘typedef’ constructs~ class and interface declarations introduce a new type

name~ inheritance hierarchy (subtype)~ structural equivalence for arrays

Chap. 5 : Data Type

Page 63: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

63

타입 검사 (Type Checking) 타입 검사 종류 (categories)

~ Dynamic Type Checking 타입 정보를 실행시간에 유지하고 검사

~ Static Type Checking 느슨한 (weakly) 자료형 검사 언어 Strongly-Typed Languages

Unspecified whether dynamic or static typing is to be used

Chap. 5 : Data Type

Page 64: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

64

Type Checking Examples C/C++

~ static type checking~ no a strongly typed language: type conversion

Scheme~ dynamic type checking but rigorous~ predefined type test functions: number?, symbol?, …

Ada~ a strongly typed language~ array bound checks are performed during run-time:

exceptions

Chap. 5 : Data Type

Page 65: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

65

Type Checking and Type Inference 타입 추론 (inference)

~ the process to infer the type of an expression from the types of its subexpressions

Type Checking and Type Inference~ Type checking rules and type inference rules are

interminglede1 + e2

~ Type checking rules are type inference rules are closely related with the type equivalence algorithm

~ Explicit declarations are helpful for type checking but not mandatory

Chap. 5 : Data Type

Page 66: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

66

Type Compatibility Relaxing the type correctness

For assignment compatibility, information preservation is an important requirement.

Language Examples~ Ada: subrange types of a base type are compatible~ C, Java: numeric types are compatible

Type Equivalence Type Compatibilitye1 + e2

e1 and e2 should be of equivalent types.

e1 and e2 should be of compatible types.

Chap. 5 : Data Type

Page 67: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

67

Implicit Types Implicit Types

~ The types of entities are not explicitly declared but inferred implicitly

Examples~ C: the types of variables and functions are implicitly intx; /* implicitly int */f(int x) { return x + 1; } /* returns int */

~ Pascal: constants are implicitly typed from the literalsconst PI = 3.14159; (* implicitly real *)

Chap. 5 : Data Type

Page 68: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

68

Type Conversion Classifying Type

Conversions~ According to the

notation Implicit Conversions

(coercion) Explicit Conversions

(casting)~ According to the sizes of

the types involved Widening

Conversions Narrowing

Conversions: may involve a loss of data

C Exampleint x = 3;x = 2.3 + x / 2;

int

double

promotion(widening)

int

double

assignmentconversion(narrowing)

Page 69: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

69

Notes on Type Conversions Advantages of Explicit Conversions

~ Type conversions are documented precisely.~ Make it easier for the translator to resolve

overloading.double max(int, double); // max #1double max(double, int); // max #2...max(2, 3); // calls what?max(2, (double)3); // calls max #1

Structure Casting~ The sizes of the structure types should be identical.~ The translation merely reinterprets the memory

Chap. 5 : Data Type

Page 70: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

70

포괄 (generic) Pointers Generic pointers may point anything.

~ anonymous pointers (void* in C)

~ C allows the both conversion to be implicit.~ In C++, the conversion 1 is implicit

but the conversion 2 should be explicit.

char *int *...

conversion 1

conversion 2void *

Chap. 5 : Data Type

Page 71: Chapter 5 Data Types SANGJI University KO Kwangman (kkman@sangji.ac.kr)

[email protected]

71

Library Functions for Conversions Ada Example

~ attribute functions of the character typecharacter'pos('a') -- returns 97character'val(97) -- returns 'a'

Java Example~ conversion functions of the Integer class

String s = Integer.toString(12345);int i = Integer.parseInt("54321");

Chap. 5 : Data Type