1 / 71

Chapter 5 Data Types

Chapter 5 Data Types. SANGJI University KO Kwangman (kkman@sangji.ac.kr). 1. Introduction. Type supports abstraction. Real World. Programming Language. Programming Language Implementation. 유한성 (finite) 추상화 (abstraction). concrete representation. Natural Numbers. int data.

lpowers
Télécharger la présentation

Chapter 5 Data Types

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. 1. Introduction • Type supports abstraction Real World Programming Language Programming Language Implementation 유한성(finite) 추상화(abstraction) concrete representation Natural Numbers int data binary digits in sizeof(int) bytes 2's complement Real Numbers double data binary digits in sizeof(int) bytes IEEE754 Chap. 5 : Data Type

  3. 타입(type) • 값의 집합과 그 값들에 대한 연산의 집합. • 정수 타입 • 값 :..., -2, -1, 0, 1, 2, ... • 연산 :+, -, *, /, <, ...로 구성 • 불 타입 • 값 : true, false • 연산 : , ,  Chap. 5 : Data Type

  4. 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

  5. 타입 오류(type error) • 어떤 연산을 해당하지 않는 타입의 값에 적용함으로써 발생하는 오류 • 어셈블리 프로그램 작성 시에 자주 발생 • 고급 언어의 경우에는 컴파일러와 실행시간 시스템이 타입 오류를 검사 및 추출 • 타입 체계(type system)는 타입 오류를 검출하기 위한 기반을 제공 Chap. 5 : Data Type

  6. 5.2 정적 및 동적 타입 결정 • 타입 체계 • 덧셈에 사용되는 값은 숫자여야 한다는 것과 같은 제약을 보장 • EBNF를 사용하여 문법적으로 표현할 수 없음. • 자료형 검사 • 컴파일 시간에 타입 검사 수행 • C 언어 • 실행 시간에 타입 검사 수행 • Perl 언어 • 두 가지 방법을 다 사용하기도 한다. • Java 언어 Chap. 5 : Data Type

  7. statically typed • 변수의 타입이 컴파일 시간에 선언에 의하여 고정 • 정적으로 타입이 결정(statically typed)되는 언어 • dynamically typed • 변수의 타입이 저장되는 값에 따라 실행 중에 볂하 • 동적으로 타입이 결정(dynamically typed )되는 언어 Chap. 5 : Data Type

  8. strongly typed 언어 • 타입 체계가 컴파일 중이나 실행 중에 모든 타입 오류를 찾아낼 수 있을 언어 • 동적 타입 결정 또는 정적 타입 결정. • 유니온(union) 타입 • 많은 언어들에서 타입 체계의 허점의 원인 • 동적으로 타입이 결정되는 언어는 각각의 값에 타입을 함께 저장 Chap. 5 : Data Type

  9. 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

  10. 중복(overloaded) • 함수나 연산자가 인수의 타입에 따라 그 의미가 달라지는 것 • a + b in Java • 정수 덧셈 • 부동소수점수 덧셈 • 문자열 접합 (concatenation) • 혼합모드 • 하나는 정수이고 다른 인수는 부동소수점수인 경우

  11. 자료형 변환 • narrowing 변환 • 원래 값보다 더 적은 수의 비트열을 결과로 생성하는 타입 변환 • widening • 묵시적 변환이 허용되지 않는 이유? Chap. 5 : Data Type

  12. 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

  13. 26 Pointer 주소 char a='A'; char *p; p = &a; ‘A’ 26 변수a 포인터p *p= 'B'; • 포인터(pointer) • 다른 변수의 주소를 가지고 있는 변수 • 포인터가 가리키는 내용의 변경: * 연산자 사용 Chap. 5 : Data Type

  14. 주소 26 &a *p 26 ‘A’ 변수 a 포인터 p • 포인터 연산자 • & 연산자 • 변수의 주소를 추출 • * 연산자 • 포인터가 가리키는 곳의 내용을 추출 Chap. 5 : Data Type

  15. 포인터의 사용 struct Node { int key; struct Node* next; }; struct Node* head; Chap. 5 : Data Type

  16. 포인터 사용에서 발생될 수 있는 문제 • 신뢰성 있는 소프트웨어의 개발을 방해. • 오류가 생기기 쉽다 • 버퍼 넘침(Buffer overflow), 메모리 누출(memory leaks) • 특히 C 에서 문제가 많이 발생함 Chap. 5 : Data Type

  17. Array, List 시작주소(base) … … … A[1] A[0] A[9] 인덱스(첨자) 배열이름 : 기억장소의 시작위치(주소) • 배열(array) • 동일 자료형(same type)의 자료들이 순서(linear) 있게 구성된 집합 • 연속된 기억 공간 차지 • 유한한 개수의 자료가 저장됨 • 직접접근 (direct access) • 기준위치에 대한 상대적 위치를 나타내는 인덱스(index)를 사용하여 가능 Chap. 5 : Data Type

  18. dsInt[0] dsInt[1] dsInt[2] 1) int dsint [] 3) 생성된 배열의 시작주소 전달 2) dsInt = new int[3] • Java에서의 배열 • 선언(declaration) • 생성될 배열 시작 위치 저장 int dsInt [] ; • 생성(creation) • 힙 메모리에서 배열 크기만큼의 기억 공간을 할당한 후 시작 주소를 배정 dsInt = new int[3] ; Chap. 5 : Data Type

  19. Homeworks • 연결 리스트 • 구조체 • 유니온 • 문자열 • 부분 범위형 Chap. 5 : Data Type

  20. still controversial Reliability (security) strongly typed language Flexibility type-less language 명시적 자료형(Explicit Typing) • 정적 자료형 검사(static type checking) • static type checking is still controversial. • 유연성(flexibility) • 자료형 결정 및 검사를 느슨 또는 반대 • 신뢰성(reliability) 또는 보안(security) • 최대한 제약성(restrictiveness) • 엄격한 번역 시간 자료형 검사 Chap. 5 : Data Type

  21. 정적 자료형 검사의 이유 1. 수행 효율성(execution efficiency) • no need to run-time type checking • 효율적인 메모리 할당 • 효율적인 목적기계 코드 생성 2.번역 효율성(Translation Efficiency) • 분리 컴파일(separate compilation) 가능 • 재컴파일시 컴파일되는 코드의 양을 줄일 수 있음 3. 작성 용이성(writability, Coding Efficiency) • 번역시에 타입 에러를 조기에 발견 Chap. 5 : Data Type

  22. 4. 보안과 신뢰성(security & reliability) • 실행시 발생 될 수 있는 에러를 사전 차단 5.판독성(readability) • 명시적 자료형 선언은 자료형 설계를 문서화 • good for documentation 6. 모호성 제거(remove ambiguity) • 다중 적재된 명칭(overloaded names)에 대한 모호성 해결(resolving) 7. … Chap. 5 : Data Type

  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 operations Fint = { +, -, *, … } Chap. 5 : Data Type

  24. 자료형 검사, 자료형 추론 • 자료형 검사(type checking) • 번역기가 프로그램내에 자료형 정보에 문제가 없는지 검사한 과정 • 연산자(서브 프로그램)과 피연산자(매개변수) 사이에 자료형의 일관성(type consistency)을 검사한 과정 • 자료형 추론(type inference) • 수식에 자료형 부착(attaching)시키는 동작 • z=x/y에서 z의 자료형을 결정하기 위해서 ? • x, y의 의 자료형이 결정되어야 함. • 상호의존족 • 자료형 검사와 자료형 추론은 상호의존적 Chap. 5 : Data Type

  25. 사용자-정의 자료형 (user-defined data type) Derived Types array, structures, … Basic Types (primitive types) int, double, … type constructors type constructors Constructing Types • 자료형 구성자(type constructors) • 기본 자료형으로 부터 새로운 자료형을 구성 • Derived types are parameterized type constructors. Chap. 5 : Data Type

  26. 자료형 선언(type declaration) • 새로운 자료형에 이름 부여 (In C example) typedef int int10[10]; Chap. 5 : Data Type

  27. 자료형 시스템(type system) • 자료형 동등성(type equivalence) 알고리즘 • 두 개의 자료형이 일치하는지 여부를 결정하는 알고리즘 • 방법 ? • 자료형 시스템(type system) • 자료형 구성 방법 • 자료형 동등성 알고리즘 • 자료형 검사, 자료형 추론 • … Chap. 5 : Data Type

  28. Typing • 엄격한 자료형(strongly-typed) 언어 • 모든 자료형 에러가 번역 시간에 발견 • 가능한 가장 이른 시점에 프로그램내의 모든 에러 발견 • 예외(exception) 검사 • 실행 도중에만 검사할 수 있는 오류s. • 불안전한 프로그램은 대부분 번역 시간에 거부 • 너무 엄격해서 적법한 프로그램까지 거부 • 적적한 자료형 정보를 프로그래머가 명시적으로 제공 • Ada, Haskell, Pascal, … Chap. 5 : Data Type

  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

  30. Safe Programs • Every well-typed programs are safe but not vice versa. contain data-corrupting errors Executable Programs Legal Programs (Safe Programs) Unsafe Programs Well-Typed Programs Chap. 5 : Data Type

  31. Predefined Simple Types Simple Types Enumeration Types User-Defined Ordinal Types Subrange Types • Defined Operators: • successor • predecessor • comparison 단순 타입(Simple Types) • 단순 타입 • atomic types • the types which contain no other type substructures • 단순 타입의 분류 Chap. 5 : Data Type

  32. Ordinal Type Example • Enumerated Type in C enum Color { Red, Green, Blue }; • Enumerated Type in Ada type Color_Type is (Red, Green, Blue); • Enumerated Type in ML datatype Color_Type = Red | Green | Blue; • Java does not have enumerated types. • Subrange Type in Ada type Digit_Type is range 0..9; Chap. 5 : Data Type

  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

  34. Type Constructors • 타입 • 집합(set) • 집합 연산이 기존의 타입에서 새로운 타입을 구성하는데 사용 • 타입 구성자(type constructor) • 집합 연산이 타입에 적용 • 데카르트 곱, 합집합, 멱집합, 함수집합, 부분집합. Chap. 5 : Data Type

  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

  36. component selector operation (structure member operation) Example: Structure Types in C struct 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) Chap. 5 : Data Type

  37. 합집합(union) • 합집합 종류 • 비구별 합집합(undiscriminated union) • normal set union • 구별 합집합(discriminated union) • 원소를 구별하기 위한 태그(tag)가 첨부 Chap. 5 : Data Type

  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

  39. 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 More Safe Union 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 ;

  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

  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 type f(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

  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

  43. 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 배열 선언시 크기 결정 Array Example: Java, Ada // a part of Figure 6.3 ... int [] x = new int[u] ; // Dynamic array allocation for (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;

  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 • 특정 원소 접근 공식 ? Row-Major: Column-Major: Chap. 5 : Data Type

  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

  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

  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

  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

  49. Some Notes on 2-Dimensional Array • Equivalences and Differences • for a constant N int a[N] ≡ int a[] ≡ int *a • for constants M and N int a[M][N] ≡ int a[][N] ≡ int (*a)[N] • beware that int a[][N] ≠ int **a • Declarations of C/C++ • declarations implies the usages int *a[N]; int (*a)[N]; Chap. 5 : Data Type

  50. Pointer(Reference) Types • Pointer(Reference) Type • 집합 연산에 대응되지 않는 타입 구성자 • 지정된 자료형을 지칭(참조)하는 모든 주소들의 집합 • 자동 쓰레기 수집에 허용되는 언어에서 포인턴 묵시적 • Java, ML, Scheme • 참조 vs. 포인터 • 참조 : 시스템 제어하에 있는 객체의 주소 • 값으로 사용 및 연산이 가해질 수 없음. • 포인터 • 값으로 사용 및 연산이 가해질 수 있음. double r = 2.3, &s = r; Chap. 5 : Data Type

More Related