C Program Design Data Types

Slides:



Advertisements
Similar presentations
1 Lecture 7  Fundamental data types in C  Data type conversion:  Automatic  Casting  Character processing  getchar()  putchar()  Macros on ctype.h.
Advertisements

1 Fundamental Data Types. 2 Declaration All variables must be declared before being used. –Tells the compiler to set aside an appropriate amount of space.
Introduction to C Programming Overview of C Hello World program Unix environment C programming basics.
0 Chap. 2. Types, Operators, and Expressions 2.1Variable Names 2.2Data Types and Sizes 2.3Constants 2.4Declarations Imperative Programming, B. Hirsbrunner,
1 Agenda Variables (Review) Example Input / Output Arithmetic Operations Casting Char as a Number (if time allow)
Variables, Data Types and I/O in C
CS 161 Introduction to Programming and Problem Solving Chapter 13 Console IO Herbert G. Mayer, PSU Status 9/8/2014 Initial content copied verbatim from.
Chapter 18 I/O in C. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Standard C Library I/O commands.
Computer Science 210 Computer Organization Introduction to C.
Types, Operators and Expressions CSE 2031 Fall /5/2015 3:59 PM.
CMPE13 Cyrus Bazeghi Chapter 18 I/O in C. CMPE Standard C Library I/O commands are not included as part of the C language. Instead, they are part.
Programming Language  C Types, Operators and Expressions 主講人:虞台文.
C Programming Lecture 4 : Variables , Data Types
C programming for Engineers Lcc compiler – a free C compiler available on the web. Some instructions.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
Chapter 18 I/O in C.
Introduction to C Programming Chapter 2 : Data Input, Processing and Output.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Fundamental Data Types, Operators and Expressions Kernighan/Ritchie: Kelley/Pohl: Chapter 2 Chapter 2, 3.
CS115 FALL Senem KUMOVA-METİN1 The Fundamental Data Types CHAPTER 3.
 Integers and Characters  Character Strings  Input and Output.
Chapter 7 C supports two fundamentally different kinds of numeric types: (a) integer types - whole numbers (1) signed (2) unsigned (b) floating types –
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 1.
Operating System Discussion Section. The Basics of C Reference: Lecture note 2 and 3 notes.html.
Tokens in C  Keywords  These are reserved words of the C language. For example int, float, if, else, for, while etc.  Identifiers  An Identifier is.
Types Chapter 2. C++ An Introduction to Computing, 3rd ed. 2 Objectives Observe types provided by C++ Literals of these types Explain syntax rules for.
1 MT258 Computer Programming and Problem Solving Tutorial 03.
The Cast Operator The cast operator converts explicitly from one data type of an expression to another. For example, if x is of type int, the value of.
Sudeshna Sarkar, IIT Kharagpur 1 I/O in C + Misc Lecture –
7. BASIC TYPES. Systems of numeration Numeric Types C’s basic types include integer types and floating types. Integer types can be either signed or unsigned.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 2.
Introduction to Computing Lecture 03: Basic input / output operations Introduction to Computing Lecture 03: Basic input / output operations Assist.Prof.Dr.
Basic Data Types & Memory & Representation
Introduction to ‘c’ language
Formatted Input and Output
Review C/C++ Programming Language
Chap. 2. Types, Operators, and Expressions
ECE Application Programming
Tokens in C Keywords Identifiers Constants
Input/output.
7. BASIC TYPES.
Fundamental of Programming (C)
EPSII 59:006 Spring 2004.
Chapter 18 I/O in C.
I/O in C + Misc Lecture Sudeshna Sarkar, IIT Kharagpur.
What to bring: iCard, pens/pencils (They provide the scratch paper)
Fundamental Data Types
Data Type.
Programming in C Input / Output.
Input and Output Lecture 4.
Programming in C Input / Output.
Introduction to the C Language
Variables In programming, we often need to have places to store data. These receptacles are called variables. They are called that because they can change.
Data Type.
Types, Operators and Expressions
A First Book of ANSI C Fourth Edition
CS111 Computer Programming
Chapter 18 I/O in C.
Lectures on Numerical Methods
Basic Types Chapter 7 Copyright © 2008 W. W. Norton & Company.
Chapter 18 I/O in C.
Your questions from last session
Programming in C Input / Output.
Fundamental Data Types
ECE 103 Engineering Programming Chapter 8 Data Types and Constants
Data Type.
DATA TYPES There are four basic data types associated with variables:
C How to Program, 6/e © by Pearson Education, Inc. All Rights Reserved.
Chapter 18 I/O in C.
ECE 120 Midterm 1 HKN Review Session.
Presentation transcript:

C Program Design Data Types 主講人:虞台文

Content Memory Concept Number Systems Basic Data Types int char float Double Data-Type Modifiers Type Conversions

C Program Design Data Types Memory Concept

Computer Architecture ALU Control CPU Input Output Memory Device Memory

Data in Memory: Bit, Byte, Word, … 2 possible values Byte: 8-bit data 256 (28) possible values Word: 16-bit data 65536 (216) possible values 0/1 0/1 0/1

Memory Space OS System Area mail Word User Area HelloWorld address 00000000 00000001 00000002 00000003 00000004 00000005 00000006 00000007 00000008 FFFFFFFB FFFFFFFC FFFFFFFD FFFFFFFE FFFFFFFF OS System Area mail User Area Word HelloWorld

C Program Design Data Types Number Systems

Number Systems Binary (0-1) Octal (0-7) Decimal (0-9) bn1bn2…b2b1b0 Octal (0-7) on1on2…o2o1o0 Decimal (0-9) dn1dn2…d2d1d0 Hexadecimal (0-9,A-F) hn1hn2…h2h1h0 Examples:

Number System Conversion Binary (0-1) bn1bn2…b2b1b0 Octal (0-7) on1on2…o2o1o0 Decimal (0-9) dn1dn2…d2d1d0 Hexadecimal (0-9,A-F) hn1hn2…h2h1h0 Examples:

Number System Conversion Decimal Binary Octal Hexadecimal 0000 1 0001 1 1 2 0010 2 2 3 0011 3 3 4 0100 4 4 5 0101 5 5 6 0110 6 6 7 0111 7 7 8 1000 10 8 9 1001 11 9 10 1010 12 A 11 1011 13 B 12 1100 14 C 13 1101 15 D 14 1110 16 E 15 1111 17 F

Number Coding in C #include <stdio.h> main() { int octNum = 011; // an octal number is prefixed by 0 int hexNum = 0x11; // a hexadecimal number is prefixed by 0x int decNum = 11; // a decimal number is w/o any prefix // display decimal numbers // for numbers represented in different number systems printf("011=%d, 0x11=%d, 11=%d\n", octNum, hexNum, decNum); // desplay a number using different number sytems printf("100=0x%x, 100=0%o, 100=%d\n", 100, 100, 100); }

Data Coding int totalMoney = 115; int motorState = 115; int girl_boy = 115; 11510 = 011100112 = 011100112 1 = 011100112 7 = 01112 3 = 00112

練習 輸入一介於0-255之十進位數字用於表示八台馬達之狀態(如前投影片所示),利用你目前所學過之C敘述撰寫一程式,輸出各台馬達之狀態。例:

練習 輸入一介於0-255之十進位數字用於表示男女孩數(如前投影片所示),利用你目前所學過之C敘述撰寫一程式,輸出男孩與女孩數。例:

C Program Design Data Types Basic Date Types

Basic Data Types char a single byte, capable of holding one character in the local character set int an integer, typically reflecting the natural size of integers on the host machine float single-precision floating point double double-precision floating point The type of an object determines the set of values it can have and what operations can be performed on it.

The sizeof Operator #include <stdio.h> main() { printf("The size of char is: %d\n", sizeof(char)); printf("The size of int is: %d\n", sizeof(int)); printf("The size of float is: %d\n", sizeof(float)); printf("The size of double is: %d\n\n", sizeof(double)); printf("The size of short is: %d\n", sizeof(short)); printf("The size of long is: %d\n", sizeof(long)); printf("The size of long double is: %d\n", sizeof(long double)); printf("The size of void* is: %d\n\n", sizeof(void *)); }

int  Signed Integer The size of int is dependent on machine It is usually the most efficient data type of a machine, e.g., in a 32-bit machine, its size is 32 bits, i.e., 4 bytes. The range of int is defined in <limits.h> #define INT_MIN (-2147483647 - 1) /* minimum (signed) int value */ #define INT_MAX 2147483647 /* maximum (signed) int value */

int  Signed Integer INT_MIN (-2147483647 - 1) INT_MAX 2147483647 #include <stdio.h> #include <limits.h> main() { int val1, val2, val3, val4; printf("int range: %d <--> %d\n", INT_MIN, INT_MAX); val1 = INT_MIN + 1; val2 = INT_MAX - 1; // within range val3 = INT_MIN - 1; val4 = INT_MAX + 1; // overflow // ok --- within range printf("INT_MIN + 1 = %d, INT_MAX - 1 = %d\n", val1, val2); // overflow printf("INT_MIN - 1 = %d, INT_MAX + 1 = %d\n", val3, val4); }

Integer Constants ASCII Integer constant can be expressed in the following ways: 1234 (decimal) 0xff (Hexidecimal) 0100 (Octal) 'a' (ASCII character) '\xhh' (Hex character) '\000' (Oct character) Overflow 由程式設計師負責 用於表示一個 Byte足夠表示之整數

Integer Constants ASCII #include <stdio.h> main() { int val1, val2, val3, val4; val1 = 'd'; val2 = '\x64'; val3 = '\144'; val4 = 'a' + 3; // Display in decimal printf("'d'=%d, '\\x64'=%d, '\\144'=%d, 'a' + 3 = %d\n", val1, val2, val3, val4); // Display in character printf("'d'->%c, '\\x64'->%c, '\\144'->%c , 'a' + 3->%c\n" }

練習 預測以下程式中哪些敘述編譯時會產生錯誤(error)或警訊(warning) , 說明其原因,編譯並驗證之。 #include <stdio.h> #include <limits.h> main() { int v1, v2, v3, v4, v5, v6, v7, v8, v9, v10; v1 = INT_MAX + 1; v2 = INT_MIN - 1; v3= 9999999999999; v4 = -9999999999999; v5 = 0x100; v6 = '\x100'; v7 = 0377; v8 = '\377'; v9 = 0477; v10 = '\477'; }

char  Signed Character CHAR_MIN (-128) CHAR_MAX 127 char  Signed Character The size of char is 8 bits (1 byte) Although it is named character, it is in fact an integer whose value can be represented by one byte, i.e., between 128 and +127. <limits.h> #define SCHAR_MIN (-128) /* minimum signed char value */ #define SCHAR_MAX 127 /* maximum signed char value */ // . . . . #define CHAR_MIN SCHAR_MIN #define CHAR_MAX SCHAR_MAX

char  Signed Character CHAR_MIN (-128) char_MAX 127 char  Signed Character The size of char is 8 bits (1 byte) Although it is named character, it is in fact an integer whose value can be represented by one byte, i.e., between 128 and +127. It is most frequently used to represent ASCII characters (7-bit) ASCII

Character Constants ASCII Character constant can be expressed in the following ways: 1234 (decimal) 0xff (Hexidecimal) 0100 (Octal) 'a' (ASCII character) '\xhh' (Hex character) '\000' (Oct character) Overflow 由程式設計師負責 用於表示一個 Byte足夠表示之整數

Character Constants Some Escape Sequences \a alert (bell) character \\  \\   backslash  \b  backspace  \?  question mark  \f  formfeed  \'  single quote  \n  newline  \"   double quote  \r  carriage return  \000  octal number  \t  horizontal tab  \xhh  hexadecimal number   \v  vertical tab

範例:Character Constants #include <stdio.h> main() { char c1, c2, c3, c4; c1 = 'd'; c2 = '\x64'; c3 = '\144'; c4 = 'a' + 3; // Display in decimal printf("'d'=%d, '\\x64'=%d, '\\144'=%d, 'a' + 3 = %d\n", c1, c2, c3, c4); // Display in character printf("'d'->%c, '\\x64'->%c, '\\144'->%c , 'a' + 3->%c\n" }

範例:Escape Sequences ASCII #include <stdio.h> main() { printf("\x6d\x6f\x64\x65\x6d\n"); }

char vs. int char與int可以說只有大小(容量)不同,可以用來存放相同性質之資料。 一般,sizeof(int) > sizeof(char) 。 故,若容量足夠,使用char較省記憶體。例如:表示年齡(age)與各科成績(math_score)之變數,用char已足夠。 然,省記憶體不意謂運算速度較快。 char與int變數間可以進行運算 char變數將先轉為int型態後,再行運算,運算後型態為int char與int資料型態之變數值可交互指派(可能overflow) C中字串(string)係char形成之陣列。

範例:char vs. int 以下程式可以通過編譯,但結果卻與預期不同 #include <stdio.h> main() { char c='d'; // c=100 int val=200; printf("c = %d, val= %d\n", c, val); val = c + val; // val = 300? printf("val = c + val = %d (Expected %d)\n", val, 300); c = c + val; // c = 400? printf("c = c + val = %d (Expected %d)\n", c, 400); val = c * 2; // val = 800? printf("val = c * 2 = %d (Expected %d)\n", val, 800); c = val; // c = 800? printf("c = val = %d (Expected %d)\n", c, 800); }

範例:char vs. int 以下程式可以通過編譯,但結果卻與預期不同 #include <stdio.h> main() { char c='d'; // c=100 int val=200; printf("c = %d, val= %d\n", c, val); val = c + val; // val = 300? printf("val = c + val = %d (Expected %d)\n", val, 300); c = c + val; // c = 400? printf("c = c + val = %d (Expected %d)\n", c, 400); val = c * 2; // val = 800? printf("val = c * 2 = %d (Expected %d)\n", val, 800); c = val; // c = 800? printf("c = val = %d (Expected %d)\n", c, 800); }

練習 試找出產生是項執行結果之原因 #include <stdio.h> main() { char c='d'; // c=100 int val=200; printf("c = %d, val= %d\n", c, val); val = c + val; // val = 300? printf("val = c + val = %d (Expected %d)\n", val, 300); c = c + val; // c = 400? printf("c = c + val = %d (Expected %d)\n", c, 400); val = c * 2; // val = 800? printf("val = c * 2 = %d (Expected %d)\n", val, 800); c = val; // c = 800? printf("c = val = %d (Expected %d)\n", c, 800); }

常用之字元輸出入函式 int getchar ( void ); int putchar ( int character ); Returns the next character from the standard input (stdin). Remark: line-based read int putchar ( int character ); Writes character to the current position in the standard output (stdout) and advances the internal file position indicator to the next position.

範例:字元輸出入函式 /* uppercase typewriter */ #include <stdio.h> main() { char c; do { c = getchar(); if(c >= 'a' && c <= 'z') c = c - 'a' + 'A'; putchar(c); } while (c != EOF); }

範例:字元輸出入函式 /* uppercase typewriter */ #include <stdio.h> main() { char c; do { c = getchar(); if(c >= 'a' && c <= 'z') c = c - 'a' + 'A'; putchar(c); } while (c != EOF); }

陣列(Arrays) 記 憶 體 Examples: score Array is a data structure that stores contiguous data elements of the same type. 200 bytes 50 400 address distance Examples: int score[50]; char address[50]; double distance[50];

陣列(Arrays) . Examples: int score[50]; char address[50]; double distance[50]; score . score[0] score[1] score[49] address distance

陣列(Arrays) . Examples: int score[50]; char address[50]; double distance[50]; score address[0] address[1] address[2] address[49] . address distance

陣列(Arrays) . Examples: int score[50]; char address[50]; double distance[50]; . distance[0] distance[49] score address distance

陣列使用注意事項 陣列之索引(index)由0開始 C Compiler對陣列索引不做out of range檢查 一陣列若含n元素,其索引由0至n-1 C Compiler對陣列索引不做out of range檢查 易產生程式錯誤,甚或系統失敗 寫程式時程式設計師應保證陣列索引不超出範圍

範例: 輸入若干位學生成績將之儲存於一整數陣列中,並求算平均成績。 #include <stdio.h> #define MAX_STUDENTS 50 int scores[MAX_STUDENTS]; // define as global main() { int i, count=0, score, sum, avg; // local variables do{ // Enter scores until a negative score is obtained printf("Enter score for student No. %d:", count + 1); scanf("%d", &score); if(score >= 0) scores[count++] = score; } while(score >= 0 && count < MAX_STUDENTS); for(i = 0, sum = 0; i < count; sum += scores[i++]);// sum all scores avg = count > 0 ? sum / count : 0; // calc average printf("The average score of %d students is %d\n", count, avg); }

練習: 修改此範例,使之於輸入所有成績完畢後,亦能將每位學生給予ABCDF等之評等,及其它數據,請自由發揮,輸出力求清晰。 #include <stdio.h> #define MAX_STUDENTS 50 int scores[MAX_STUDENTS]; // define as global main() { int i, count=0, score, sum, avg; // local variables do{ // Enter scores until a negative score is obtained printf("Enter score for student No. %d:", count + 1); scanf("%d", &score); if(score >= 0) scores[count++] = score; } while(score >= 0 && count < MAX_STUDENTS); for(i = 0, sum = 0; i < count; sum += scores[i++]);// sum all scores avg = count > 0 ? sum / count : 0; // calc average printf("The average score of %d students is %d\n", count, avg); }

範例:陣列之定義 #include <stdio.h> main() { int array1[]={0, 10, 20, 30, 40}; // initialize its elements only int array2[10]={0, 10, 20, 30, 40}; // specify size and initialize some leading elements int array3[10]; // specify size only int i; printf("Size of array1 is: %d\n", sizeof(array1)); printf("Size of array2 is: %d\n", sizeof(array2)); printf("Size of array3 is: %d\n\n", sizeof(array3)); printf("#element in array1 is: %d\n", sizeof(array1)/sizeof(int)); printf("#element in array2 is: %d\n", sizeof(array2)/sizeof(int)); printf("#element in array3 is: %d\n", sizeof(array3)/sizeof(int)); for(i=0; i < 10; i++) printf("array1[%d]=%8d,\tarray2[%d]=%8d,\tarray3[%d]=%8d\n", i, array1[i], i, array2[i], i, array3[i]); }

範例:陣列之定義 Debugging Mode執行結果 #include <stdio.h> main() { int array1[]={0, 10, 20, 30, 40}; // initialize its elements only int array2[10]={0, 10, 20, 30, 40}; // specify size and initialize some leading elements int array3[10]; // specify size only int i; printf("Size of array1 is: %d\n", sizeof(array1)); printf("Size of array2 is: %d\n", sizeof(array2)); printf("Size of array3 is: %d\n\n", sizeof(array3)); printf("#element in array1 is: %d\n", sizeof(array1)/sizeof(int)); printf("#element in array2 is: %d\n", sizeof(array2)/sizeof(int)); printf("#element in array3 is: %d\n", sizeof(array3)/sizeof(int)); for(i=0; i < 10; i++) printf("array1[%d]=%8d,\tarray2[%d]=%8d,\tarray3[%d]=%8d\n", i, array1[i], i, array2[i], i, array3[i]); } Debugging Mode執行結果

範例:陣列之定義 對未定義初值之陣列元素值勿做預測 Release Mode執行結果 #include <stdio.h> main() { int array1[]={0, 10, 20, 30, 40}; // initialize its elements only int array2[10]={0, 10, 20, 30, 40}; // specify size and initialize some leading elements int array3[10]; // specify size only int i; printf("Size of array1 is: %d\n", sizeof(array1)); printf("Size of array2 is: %d\n", sizeof(array2)); printf("Size of array3 is: %d\n\n", sizeof(array3)); printf("#element in array1 is: %d\n", sizeof(array1)/sizeof(int)); printf("#element in array2 is: %d\n", sizeof(array2)/sizeof(int)); printf("#element in array3 is: %d\n", sizeof(array3)/sizeof(int)); for(i=0; i < 10; i++) printf("array1[%d]=%8d,\tarray2[%d]=%8d,\tarray3[%d]=%8d\n", i, array1[i], i, array2[i], i, array3[i]); } Release Mode執行結果

字串(String) char str[]="hello\n"; C語言沒有定義字串資料型態 C語言之字串係以零(NUL)作為結尾之字元陣列(char array)表示 例: h (68) e (65) l (6C) o (6F) \n (0A) \0 (00) str str[0] str[1] str[2] char str[]="hello\n"; str[3] str[4] str[5] str[6] sizeof(str) = 7

範例: 輸入一行文字將之儲存於一字串陣列中,並將之轉換成大寫後輸出。 #include <stdio.h> #define MAX_LINE 256 char line[MAX_LINE]; // buffer to hold a null terminated string main() { int i=0; char c; do{ // read a line in safe mode c = getchar(); line[i++] = c; } while(c != '\n' && i < (MAX_LINE - 1)); // out of range check by programmer line[i] = '\0'; // string is null terminated // convert a line to ucase i = 0; while((c = line[i]) != '\0'){ line[i] = c >= 'a' && c <= 'z' ? c - 'a' + 'A' : c; i++; } printf("\n%s\n", line); // output ucase line

範例: 輸入一行文字將之儲存於一字串陣列中,並將之轉換成大寫後輸出。 #include <stdio.h> #define MAX_LINE 256 char line[MAX_LINE]; // buffer to hold a null terminated string main() { int i=0; char c; do{ // read a line in safe mode c = getchar(); line[i++] = c; } while(c != '\n' && i < (MAX_LINE - 1)); // out of range check by programmer line[i] = '\0'; // string is null terminated // convert a line to ucase i = 0; while((c = line[i]) != '\0'){ line[i] = c >= 'a' && c <= 'z' ? c - 'a' + 'A' : c; i++; } printf("\n%s\n", line); // output ucase line

範例: 簡化版 輸入一行文字將之儲存於一字串陣列中,並將之轉換成大寫後輸出。 #include <stdio.h> #define MAX_LINE 256 char line[MAX_LINE]; // buffer to hold a null terminated string main() { int i=0; char c; do{ // read a line in safe mode c = getchar(); line[i++] = c; } while(c != '\n' && i < (MAX_LINE - 1)); // out of range check by programmer line[i] = '\0'; // string is null terminated // convert a line to ucase i = 0; while((c = line[i]) != '\0'){ line[i] = c >= 'a' && c <= 'z' ? c - 'a' + 'A' : c; i++; } printf("\n%s\n", line); // output ucase line do{ // read a line in safe mode line[i++] = c = getchar(); } while(c != '\n' && i < (MAX_LINE - 1)); // out of range check by programmer while(c = line[i]) line[i++] = c >= 'a' && c <= 'z' ? c - 'a' + 'A' : c;

練習: 製作一C程式,從標準輸入裝置成功的讀取一十進制整數字串(可能含正負號) , 並將之儲存於一字元陣列中。 將上題儲存於陣列中之字串轉換成整數,並呼叫printf將之印出,以驗證你的轉換是否正確。

Float and Double IEEE 754

Header Files <limits.h> and <float.h>

Floating Point Constants Floating point constants contain a decimal point or exponent. By default they are double. 123.4 (double) 1e-2 (double) 124.4f (float) 1e-2f (float)

範例: a2 + b2 = c2 畢氏定理(Pythagorean theorem ) #include <stdio.h> #include <math.h> main() { double a, b; printf("Enter two legs a and b of a right triangle:"); scanf("%lf%lf",&a,&b); printf("The hypotenuse c of the triangle is %10.5lf\n", sqrt(a * a + b * b )); }

範例: a2 + b2 = c2 畢氏定理(Pythagorean theorem ) #include <stdio.h> #include <math.h> main() { double a, b; printf("Enter two legs a and b of a right triangle:"); scanf("%lf%lf",&a,&b); printf("The hypotenuse c of the triangle is %10.5lf\n", sqrt(a * a + b * b )); }

練習: 參考http://zh.wikibooks.org/wiki/%E4%B8%89%E8%A7%92%E5%87%BD%E6%95%B8製作一C程式,列印出sin, cos, tan表格。 求二元一次方程式(ax2 + bx + c = 0)之解,需考慮有兩組實解、有兩組虛解及僅單一解之情況。

C Program Design Data Types Data-Type Modifiers

Basic Data Types char a single byte, capable of holding one character in the local character set int an integer, typically reflecting the natural size of integers on the host machine float single-precision floating point double double-precision floating point

Modifiers short long signed unsigned

Data Types in Real World bytes bits range char 1 8 128  127 unsigned char 0  255 short int 2 16 32,768  32,767 unsigned short int 0 65,535 int 4 32 -2,147,483,648  +2,147,483,647 unsigned int 0  4,294,967,295 long int unsigned long int float single-precision floating point double 64 double-precision floating point long double extended-precision floating point

Data Types in Real World bytes bits range char 1 8 128  127 unsigned char 0  255 short int 2 16 32,768  32,767 unsigned short int 0 65,535 int 4 32 -2,147,483,648  +2,147,483,647 unsigned int 0  4,294,967,295 long int unsigned long int float single-precision floating point double 64 double-precision floating point long double extended-precision floating point type bytes bits range char 1 8 128  127 unsigned char 0  255 short int 2 16 32,768  32,767 unsigned short int 0 65,535 int 4 32 -2,147,483,648  +2,147,483,647 unsigned int 0  4,294,967,295 long int unsigned long int float single-precision floating point double 64 double-precision floating point long double extended-precision floating point

On Integer Data Types

範例: Sizes of C Data Types #include <stdio.h> /* view the sizes of C basic data types */ int main() { printf("sizeof(char) == %d\n", sizeof(char)); printf("sizeof(short) == %d\n", sizeof(short)); printf("sizeof(int) == %d\n", sizeof(int)); printf("sizeof(long) == %d\n", sizeof(long)); printf("sizeof(float) == %d\n", sizeof(float)); printf("sizeof(double) == %d\n", sizeof(double)); printf("sizeof(long double) == %d\n", sizeof(long double)); return 0; }

C Program Design Data Types Type Conversions

Type Hierarchies narrow wider single-precision floating point bytes bits range char 1 8 128  127 unsigned char 0  255 short int 2 16 32,768  32,767 unsigned short int 0 65,535 int 4 32 -2,147,483,648  +2,147,483,647 unsigned int 0  4,294,967,295 long int unsigned long int float single-precision floating point double 64 double-precision floating point long double extended-precision floating point wider narrow

Type Conversions Implicit type conversion Explicit type conversion also known as coercion automatically done by the compiler when type mismatch on operands narrower type  wider type Explicit type conversion also known as casting done by programmer

Implicit Type Conversion General rules for binary operators (+-*/%etc) If either operand is long double the other is converted to long double. Otherwise, if either operand is double the other is converted to double Otherwise, if either operand is float the other is converted to float Otherwise, convert char and short to int Then, if an operand is long convert the other to long.

範例:Implicit Type Conversion int a; unsigned long b; float f, g; double d; g = a + f; // a transforms to float d = a + b; // a and b transform to unsigned long, adding // is produced in unsigned long domain and then // the result type unsigned long is transformed // to double

練習:Implicit Type Conversion 預測右方程式將產生之輸出為何?編譯執行後驗證你的預測是否正確? 說明C編譯器在編譯右方程式時,將對各assignment做哪些implicit type conversions ?

Explicit Type Conversion: Casting (type name) expression

(type name) expression 範例:Type Casting

(type name) expression 範例:Type Casting

(type name) expression 範例:Type Casting

(type name) expression 範例:Type Casting

(type name) expression 範例:Type Casting

More on Type Casting (type name) expression The cast operator has the same high precedence as other unary operators.