chapter 3: the fundamental data types

36
COMPUTER SCIENCE, KOREA UNIVE RSITY Chapter 3: The Fundamental Data Types Rim, Hae-Chang Department of Computer Science and Engineering Korea University

Upload: brosh

Post on 23-Jan-2016

55 views

Category:

Documents


0 download

DESCRIPTION

Chapter 3: The Fundamental Data Types. Rim, Hae-Chang Department of Computer Science and Engineering Korea University. Contents. 3.1 Declarations, Expressions and Assignment( 선언 , 표현식 , 대입 ) 3.2 Fundamental Data Types in C (C 에 쓰이는 기본 데이터 타입 ) - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Chapter 3: The Fundamental Data Types

COMPUTER SCIENCE, KOREA UNIVERSITY

Chapter 3: The Fundamental Data Types

Rim, Hae-Chang

Department of Computer Science and Engineering

Korea University

Page 2: Chapter 3: The Fundamental Data Types

Natural Language Processing Lab, Korea University 2

Contents

3.1 Declarations, Expressions and Assignment( 선언 , 표현식 , 대입 )

3.2 Fundamental Data Types in C (C 에 쓰이는 기본 데이터 타입 )

3.3 Characters and Data Type char (문자와 char 타입 )

3.4 The Data Type int (int 타입 )

3.5 The Integral Types short,long,and unsigned (short,long,and unsigned 정수 타입들 )

3.6 The Floating Types ( 실수 타입들 )

3.7 Use of typedef (typedef 연산자의 사용 )

3.8 The sizeof operator (sizeof 연산자 )

3.9 Assignment Operators ( 배정 연산자 )

3.10 The Use of getchar() and putchar()

3.11 Conversions and Casts ( 변환과 캐스트 )

3.12 Hexadecimal and Ocatal Constants(16/8 진수 상수 )

Page 3: Chapter 3: The Fundamental Data Types

Natural Language Processing Lab, Korea University 3

3.1.Declarations, Expressions and Assignment

Declarations ( 선언 ) declaration ::= type var {= value}opt {, var {= value}opt }0+

메모리에 type 이 요구하는 만큼의 저장공간 ( 변수 ) 을 만들고 , 여기에 var 라는 이름을 붙이는 작업 . 변수는 선택적으로 value 로 초기화할 수 있다 .

Valid within a block consisting of declarations and statements

e.g.) char c;int a, b;float x, y = 3.3, z = -7.7;

Page 4: Chapter 3: The Fundamental Data Types

Natural Language Processing Lab, Korea University 4

3.1.Declarations, Expressions and Assignment

Expressions( 표현식 or 수식 ) Combinations of constants, variables, operators, and function

calls e.g.) 3.14;

x;sqrt(2.0);3.14 + x*y – 0.5*sin(z);

Assignment ( 대입 or 배정 ) variable = expression ; e.g.) i = 7;

x = x + 1;Y = x + sin(2*3.14);

Page 5: Chapter 3: The Fundamental Data Types

Natural Language Processing Lab, Korea University 5

3.2 Fundamental Data Types in C(C 에서 사용되는 기본 타입 )

Character types ( 문자 타입 )signed char = charunsigned char

Integer types ( 정수 타입 )signed short int = shortunsigned short int = unsigned shortsigned int = intunsigned int = unsignedsigned long int = longunsigned long int = unsigned long

Real number types ( 실수 타입 )floatdouble long double

Page 6: Chapter 3: The Fundamental Data Types

Natural Language Processing Lab, Korea University 6

3.3 Characters and Data Type char( 문자와 char 타입 )

char 1 byte. 8-bit 크기의 아스키 코드를 담을 수 있음 . 작은 크기의 정수로도 쓸 수 있다 .

signed char : –27 ~ 27 –1 unsigned char : 0 ~ 28 –1

Character constants ( 문자 상수 ) Integer type with the range same as char e.g.) char c = ’a’;

printf(”%c”,c);/* 문자로 */printf(”%d”,c);/* 숫자로 */printf(”%c%c%c”,c,c+1,c+2);

a 97 abc

Page 7: Chapter 3: The Fundamental Data Types

Natural Language Processing Lab, Korea University 7

ASCII for Letters and Digits( 문자 및 숫자 )

Character constants

Corresponding values

Character constants

Corresponding values

Character constants

Corresponding values

'a' 'b' 'c' ... 'z'97 98 99 ... 122

'A' 'B' 'C' ... 'Z'65 66 67 ... 90

'0' '1' '2' ... '9'48 49 50 ... 57

몇몇 문자 상수들과 이에 대응하는 정수값들

ASCII ( 아스키 ) 코드 전체는 부록의 표를 참고하기 바람 .

Page 8: Chapter 3: The Fundamental Data Types

Natural Language Processing Lab, Korea University 8

ASCII for Special Characters( 특수문자 )

Name of character Written in C

Hexa

valueInteger value

alertbackslashbackspacecarriage returndouble quoteform feedhorizontal tabnew linenull charactersingle quotevertical tab

\a\\ \b\r \" \f \t \n\0\' \v

075C080D220C090A00270B

792 8133412 910 03911

Page 9: Chapter 3: The Fundamental Data Types

Natural Language Processing Lab, Korea University 9

특수문자 출력하기 Bell

printf(”%c”, ’\a’); ’\a’, ’\7’, ’\07’, ’\007’, ’\0x07’

Single quote printf(”’abc\’”); printf(”%cabc%c”,’\’’,’\’’);

Double quote printf(”\”abc\””); printf(”%cabc%c”, ’\”’, ’\”’);

Back slash printf(”\\abc\\”); printf(”%cabc%c”,’\\’,’\\’);

Page 10: Chapter 3: The Fundamental Data Types

Natural Language Processing Lab, Korea University 10

3.4 The Data Type int(int 타입 )

int 4-byte word machine(32 비트 CPU,32 비트 컴파일러 ( 예 : Visual C+

+/GCC) 의 경우 :

–231 ~ +231 – 1 : –2,147,483,648 ~ +2,147,483,647 2-byte word machine(16 비트 CPU/16 비트 컴파일러 ( 예 : Turbo C))

의 경우 :

–215 ~ +215 – 1 : –32,768 ~ +32,767 최대 및 최소치 : MAX_INT, MIN_INT (<limits.h> 에 정의되어 있음 )

Interger overflow ( 정수최대허용치 초과 )#define BIG 2000000000 /* 2 billion */int a, b = BIG, c = BIG;

a = b + c; /* OUT OF RANGE ? */ ...

Page 11: Chapter 3: The Fundamental Data Types

Natural Language Processing Lab, Korea University 11

3.5 The Integral Types short,long,and unsigned

short 2-byte integer –215 ~ +215 – 1 : –32,768 ~ +32,767

long 4-byte integer –231 ~ +231 – 1 : –2,147,483,648 ~ +2,147,483,647

Page 12: Chapter 3: The Fundamental Data Types

Natural Language Processing Lab, Korea University 12

unsigned (= unsigned int) Min = 0 Max

4-byte word machines : +232 – 1 = +4,294,967,295 2-byte word machines : +216 – 1 = +65,535

Unsigned short 0 ~ +216 – 1

Unsigned long 0 ~ +232 – 1

3.5 The Integral Types short,long,and unsigned

Page 13: Chapter 3: The Fundamental Data Types

Natural Language Processing Lab, Korea University 13

3.5 The Integral Types short,long,and unsigned

정수 상수에 붙이는 접미어

u or Ul or Lul or UL

unsignedlongunsigned long

37U37L37UL

Page 14: Chapter 3: The Fundamental Data Types

Natural Language Processing Lab, Korea University 14

3.6 The Floating Types( 실수 타입 )

Floating Type 이란 ? ‘ 실수타입’이 아니라 ‘부동 ( 浮動 ) 소수점 실수 타입’으로 불러야

함 .

실수 표현의 종류 :

고정 소수점 (Fixed Point) 실수 타입 : 일반적인 표현– 125.5679, 78.6, ….

부동소수점 (Floating Point) 실수 타입 : 지수와 가수로 나누어 표현– 125.5679 = 0. 1255679 e +4 ( 가수 ) ( 지수 )

– 따라서 , 실수 타입의 메모리 크기에 따라 다음이 달라짐 :

가수에서 표현할 수 있는 소수점 이하 유효숫자의 개수 (precision) 지수에서 표현할 수 있는 실수값 범위 (range)

Page 15: Chapter 3: The Fundamental Data Types

Natural Language Processing Lab, Korea University 15

3.6 The Floating Types( 실수 타입 )

float 4-byte : (32 비트 ) 가수 유효숫자 : log10(223)=6.923 ( 즉 , 소수점 이하 6 자리까지 ) 지수 범위 : 22(8-1)=1038.531839… 즉 , e-38~e+38까지 표현 숫자표현 범위 : 0.d1d2…d6 e-38~+38

double

8-byte (64 비트 ) 가수 유효숫자 : log10(252)=15.653 ( 즉 , 소수점 이하 15 자리까지 ) 지수 범위 : 22(11-1)=10308.254… 즉 , e-308~e+308까지 표현 숫자표현 범위 : 0.d1d2…d15 e-308~+308

long double 8-byte 혹은 그 이상 (Visual C++ 에서는 8byte, GCC 에서는 12byte)

참고 : 각 실수타입의 최대최소값 알아보기 실수 타입은 컴파일러마다 조금씩 최대최소치가 다르게 설정되어 있다 . <float.h> 파일을 열고 확인한다 . FLT_MAX, FLT_MIN(float 타입 ), DBL_MAX, DBL_MIN(double 타입 ), LDBL_MAX,LD

BL_MIN(long double 타입 )

1 비트 :부호

8 비트 : 지수(exponent)

23 비트 : 가수(fraction)

1 비트 : 부호 11 비트 : 지수 52 비트 : 가수

Page 16: Chapter 3: The Fundamental Data Types

Natural Language Processing Lab, Korea University 16

3.6 The Floating Types( 실수 타입 )

실수 상수 표현하기 floating_constant ::= f_constant {f_suffix}opt

f_constant ::= f_part {.f_part}opt {e_part}opt

| f_part . {e_part}opt

| . f_part {e_part}opt

f_part ::= {digit}1+

e_part ::= {e|E}1{+|–}opt{digit}1+

f_suffix ::= f | F | l | L

실수 상수 에 쓰이는 접미어

C 에선 접미어를 붙이지 않으면 자동으로 double 로 취급함 e.g.) 3.14159L, 314.159e-2F, 0e0, 1., .5

f or F l or L

floatlong double

3.7F3.7L

Page 17: Chapter 3: The Fundamental Data Types

Natural Language Processing Lab, Korea University 17

3.7 Use of typedef

데이터 타입을 프로그래머가 새로 정의할 수 있게 하는 키워드 .

Examplestypedef char byte1;typedef int byte4;typedef float real;byte1 c; char c;byte4 i; int i;real x; float x;

Page 18: Chapter 3: The Fundamental Data Types

Natural Language Processing Lab, Korea University 18

3.8 The sizeof operator

sizeof 메모리에 만들어진 데이터의 크기를 알려주는 연산자 Syntax : sizeof(operand)

Exampleschar c, s[100]; int i;sizeof(char) 1sizeof(int) 4sizeof(i) 4sizeof(10) 4sizeof(10+500) 4sizeof(s) 100( 배열의 요소 개수 )

Page 19: Chapter 3: The Fundamental Data Types

Natural Language Processing Lab, Korea University 19

Example C Source Code :sizeof.c/* Compute the size of some fundamental types. */

#include <stdio.h>

int main(void){ printf(" char:%3d\n", sizeof(char)); printf(" short:%3d\n", sizeof(short)); printf(" int:%3d\n", sizeof(int)); printf(" long:%3d\n", sizeof(long)); printf(" unsigned:%3d\n", sizeof(unsigned)); printf(" float:%3d\n", sizeof(float)); printf(" double:%3d\n", sizeof(double)); printf("long double:%3d\n", sizeof(long double)); return 0;}

Page 20: Chapter 3: The Fundamental Data Types

Natural Language Processing Lab, Korea University 20

3.9 The Use of getchar() and putchar()

getchar() and putchar() “stdio.h” 에 선언되어 있다 . 실제로 , “stdio.h” 에 매크로로 만들어져 있다 .

#define getchar() getc(stdin) #define putchar(x) putc(x, stdout)

getchar() 키보드로부터 한 문자 (1 바이트 ) 를 읽어들이는 함수 .

putchar() 스크린에 한 문자 (1 바이트 ) 를 쓰는 함수 .

Page 21: Chapter 3: The Fundamental Data Types

Natural Language Processing Lab, Korea University 21

Example C Source Code : capitalize.c

#include <stdio.h>

int main(void){ int c;

while ((c = getchar()) != EOF) { if ('a' <= c && c <= 'z') /* lower case ? */ putchar(c + 'A' - 'a'); /* uppercase 로 변환 */ else putchar(c); } return 0;}

Page 22: Chapter 3: The Fundamental Data Types

Natural Language Processing Lab, Korea University 22

3.10 Mathematical Functions ( 수학 함수 )

Mathematical functions 표준 라이브러리에 정의되어 있음 “math.h” 를 포함 (#include) 해야 함

Examples sqrt(), pow(), exp(), log() sin(), cos(), tan() abs(), fabs()

Page 23: Chapter 3: The Fundamental Data Types

Natural Language Processing Lab, Korea University 23

Example C Source Code : power_square.c

#include <math.h>#include <stdio.h>

int main(void){ double x; while (1) { printf("Input x: "); if (scanf("%lf",&x)!=1) break; if (x >= 0.0) printf("\n%15s%22.15e\n%15s%22.15e\n%15s%22.15e\n\n", "x = ", x, "sqrt(x) = ", sqrt(x), "pow(x,x) = ", pow(x,x)); else printf("\nYour number must be nonnegative.\n\n"); } return 0;}

Page 24: Chapter 3: The Fundamental Data Types

Natural Language Processing Lab, Korea University 24

3.11 Conversions and Casts( 변환과 캐스트 )

The data types of expressions are changed implicitly or explicitly

Automatic Conversions ( 자동 타입변환 ; 암시적 타입변환 ) Coercion( 강제변환 )/Promotion( 승격 )/Demotion( 격하 ) 로도

불림 Implicit data type conversions

Casts ( 캐스트 ; 명시적 타입변환 ) Explicit data type conversions

Page 25: Chapter 3: The Fundamental Data Types

Natural Language Processing Lab, Korea University 25

Integral Promotions( 정수 타입의 승격 )

If all the values of the original type (char, short, enum) can be represented by an int, then the value is converted to an int

Otherwise, it is converted to an unsigned int

e.g) char c=’A’; printf(”%c\n”,c); => The char variable C occurs by itself as an argumen

t to printf(). However, because of integral promotion the type of the expression C is int, not char.

Page 26: Chapter 3: The Fundamental Data Types

Natural Language Processing Lab, Korea University 26

Usual Arithmetic Conversions( 일반적인 수치 변환 )

수치 타입이 연산자에 쓰일 경우 적용되는 규칙들 :

long double and X : X long double Otherwise, double and X : X double Otherwise, float and X : X float

◦ e.g.) int i;float f;double d;i + f; /*i 가 float 로 자동변환됨 */f + d; /* f 가 double 로 자동변환됨 */

( 뒷장에서 계속 )

Page 27: Chapter 3: The Fundamental Data Types

Natural Language Processing Lab, Korea University 27

Usual Arithmetic Conversions( 일반적인 수치 변환 )

Otherwise, 모든 연산자에 대해 정수타입 승격이 이루어지고 , 아래의 규칙이 적용됨

unsigned long and X : X unsigned long long and unsigned :

– If long can represent all the values of unsigned, then unsigned long

– Otherwise, both operands are converted to unsigned long long and X : X long unsigned and X : X unsigned 앞에 나열한 모든 경우에 해당하지 않을 때 : 연산자의 타입은 자동으로 int.

◦ e.g.) unsigned int ui; int i; long l;ui + i; /*i 가 unsigned int 로 자동변환됨 */i + l; /* i 가 long 으로 자동변환됨 */

Page 28: Chapter 3: The Fundamental Data Types

Natural Language Processing Lab, Korea University 28

Example of Automatic Conversion

Declarations

char c; short s; int i;long l; unsigned u; unsigned long ul;float f; double d; long double ld;

Expression Type Expression Type

c - s / iu * 2.0 - ic + 3 c + 5.0d + s2 * i / l

intdoubleintdoubledoublelong

u * 7 - if * 7 - i 7 * s * ulld + cu - ulu - l

unsignedfloatunsigned longlong doubleunsigned long시스템에 따라 다름

Page 29: Chapter 3: The Fundamental Data Types

Natural Language Processing Lab, Korea University 29

Promotion and Demotion in Assignments( 대입 연산에서의 타입승격 및 타입격하 )

In assignment statements, the type of right hand side is converted into the type of left hand side

Exampleint i;double d;d = i; /*i 가 double 로 승격됨 */

i = d; /*d 가 int 로 격하됨 */

Page 30: Chapter 3: The Fundamental Data Types

Natural Language Processing Lab, Korea University 30

Casts ( 캐스트 )

Casts 캐스트 연산자를 통한 명시적인 타입변환 . 원래의 값은 불변 . Syntax : ( 원하는 타입 ) 변수 혹은 상수

(double) i /*i 가 정수일 때 , 이 변수의 타입을 double 로 한다 */`

e.g.)(long)(‘A’+10)f=(float)((int)d+1)d=(double)i/3;(double)(x=77)

(double)x=77 /*에러 . ((double)x)=77 인데 . 이

미 상수로 바뀐 후이므로 값을 대입 할 수 없다 .*/

Page 31: Chapter 3: The Fundamental Data Types

Natural Language Processing Lab, Korea University 31

3.12 Hexadecimal and Octal Constants(16 진수 및 8 진수 상수 )

Binary bnbn-1…b2b1b0 = bn 2n + bn-1 2n-1 + … + b2 22 + b1 21 + b0 20

e.g.) 1010 = 1 23 + 0 22 + 1 21 + 0 20 = 10

Hexadecimal hnhn-1…h2h1h0 = hn 16n + hn-1 16n-1 + … + h2 162 + h1 161 + h0 160

e.g.) A7F = 10 162 + 7 161 + 15 160 = 2687

Octal OnOn-1…O2O1O0 = On 8n + On-1 8n-1 + … + O2 82 + O1 81 + O0 80

75301=7 84 + 7 83 +7 82 + 7 81 + 7 80 = 223045

Page 32: Chapter 3: The Fundamental Data Types

Natural Language Processing Lab, Korea University 32

Binary and Hexadecimal(2 진수와 16 진수 )

Decimal Binary Hexa Decimal Binary Hexa

0

1

2

3

4

5

6

7

0000

0001

0010

0011

0100

0101

0110

0111

0

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

1000

1001

1010

1011

1100

1101

1110

1111

8

9

A

B

C

D

E

F

2 진수와 16 진수 사이의 관계

Page 33: Chapter 3: The Fundamental Data Types

Natural Language Processing Lab, Korea University 33

Binary, Hexadecimal, and Octal(2 진수 , 16 진수 , 8 진수 )

Decimal Binary Hexa Octal

0

1

2

3

188

255

00000000

00000001

00000010

00000011

10111100

11111111

00

01

02

03

BC

FF

000

001

002

003

274

377

10 진수 - 2 진수 -16 진수 -8 진수 사이의 관계

Page 34: Chapter 3: The Fundamental Data Types

Natural Language Processing Lab, Korea University 34

Example Code: Conversion Using printf()

/* Decimal, hexadecimal, octal conversions. */

#include <stdio.h>

int main(void){ printf("%d %x %o\n",19,19,19); /* 19 13 23 */ printf("%d %x %o\n",0x1c,0x1c,0x1c); /* 28 1c 34 */ printf("%d %x %o\n",017,017,017); /* 15 f 17 */ printf("%d\n",11+0x11+011); /* 37 */ printf("%x\n",2097151); /* 1fffff */ printf("%d\n",0x1FfFFf); /* 2097151 */ return 0;}

Page 35: Chapter 3: The Fundamental Data Types

Natural Language Processing Lab, Korea University 35

부록 : ASCII - 1Dec Hex Char Dec Hex Char Dec Hex Char--------------------------------------------------------------------0 00 NUL '\0' 20 14 DC4 40 28 ( 1 01 SOH 21 15 NAK 41 29 ) 2 02 STX 22 16 SYN 42 2A * 3 03 ETX 23 17 ETB 43 2B + 4 04 EOT 24 18 CAN 44 2C , 5 05 ENQ 25 19 EM 45 2D - 6 06 ACK 26 1A SUB 46 2E . 7 07 BEL '\a' 27 1B ESC 47 2F / 8 08 BS '\b' 28 1C FS 48 30 0 9 09 HT '\t' 29 1D GS 49 31 1 10 0A LF '\n' 30 1E RS 50 32 2 11 0B VT '\v' 31 1F US 51 33 3 12 0C FF '\f' 32 20 SPACE 52 34 4 13 0D CR '\r' 33 21 ! 53 35 5 14 0E SO 34 22 " 54 36 6 15 0F SI 35 23 # 55 37 7 16 10 DLE 36 24 $ 56 38 8 17 11 DC1 37 25 % 57 39 9 18 12 DC2 38 26 & 58 3A : 19 13 DC3 39 27 ' 59 3B ;

Page 36: Chapter 3: The Fundamental Data Types

Natural Language Processing Lab, Korea University 36

부록 : ASCII - 2

Dec Hex Char Dec Hex Char Dec Hex Char Dec Hex Char

-----------------------------------------------------------------------------

60 3C < 80 50 P 100 64 d 120 78 x

61 3D = 81 51 Q 101 65 e 121 79 y

62 3E > 82 52 R 102 66 f 122 7A z

63 3F ? 83 53 S 103 67 g 123 7B {

64 40 @ 84 54 T 104 68 h 124 7C |

65 41 A 85 55 U 105 69 i 125 7D }

66 42 B 86 56 V 106 6A j 126 7E ~

67 43 C 87 57 W 107 6B k 127 7F DEL

68 44 D 88 58 X 108 6C l

69 45 E 89 59 Y 109 6D m

70 46 F 90 5A Z 110 6E n

71 47 G 91 5B [ 111 6F o

72 48 H 92 5C \ '\\' 112 70 p

73 49 I 93 5D ] 113 71 q

74 4A J 94 5E ^ 114 72 r

75 4B K 95 5F _ 115 73 s

76 4C L 96 60 ` 116 74 t

77 4D M 97 61 a 117 75 u

78 4E N 98 62 b 118 76 v

79 4F O 99 63 c 119 77 w