1 chapter 6 the fundamental data types. 2 outline declarations and expressions fundamental data...
Post on 20-Dec-2015
224 views
TRANSCRIPT
1
Chapter 6
The Fundamental Data Types
2
Outline
Declarations and expressionsFundamental data types
Characters and the data type char The Data type int and the integral types The floating types
The sizeof OperatorMathematical FunctionsConversions and Casts
3
Declarations and Expressions
Declarations All variables must be declared before they
can be used. Why?
4
Declarations and Expressions
Appropriate amount of space in memory should be set aside to each variable to hold its value
Declaration of a variable tells the compiler its data type.
Reason 1: Declarations enable the compiler to set aside an appropriate amount of space in memory to hold values associated with variables.
5
Declarations and ExpressionsExample: applying division on different data types
int a=5, b=2, c=a/b; float a=5, b=2, c=a/b; Machine instructions used are different
Different machine instructions are used when an operator applied on different data types
Reason 2: Declarations enable the compile to instruct the machine to perform specified operations correctly.
The programmer need not be concerned about the difference, but the C compiler has to recognize the difference and give the appropriate machine instructions
6
Declarations and Expressions
Declarations: Summary
All variables must be declared before they can be used.
o Tell the compiler to set aside an appropriate amount of space in memory to hold values associated with variables.
o Enable the compile to instruct the machine to perform specified operations correctly.
7
Declarations and Expressions
Expressions Meaningful combinations of
constants, variables, and function calls.
Most expressions have both a value and a type
8
Declarations and ExpressionsExamples of expressionsDeclarations: int a =12, b=10, c, d;Function min(int x, int y), returns the minimum value of x and y.
Examples of expressions: exp1, function call min(var1, var2): min(a,b) exp2, var * constant: a*12 exp3, function call min(exp1, exp2): min(min(a,b), a*12) exp4, exp3+exp1: min(min(a,b), a*12) +
min(a,b) exp5, var = exp3: c = min(min(a,b), a*12) exp6, var = exp5: d = c = min(min(a,b), a*12)
9
Declarations and Expressions
Summary Declarations:
All variables must be declared before they can be used.
o Tell the compiler to set aside an appropriate amount of space in memory to hold values of variables.
o Enable the compile to instruct the machine to perform specified operations correctly.
ExpressionMeaningful combination of constants,
variables, and function calls.Most expressions have both a value and a
type
10
Outline
Declarations and expressionsFundamental data types
Characters and the data type char The Data type int and the integral types The floating types
The sizeof OperatorMathematical FunctionsConversions and Casts
11
The Fundamental Data Types
Integral types The types that can be used to hold integer
values.Characters: char, signed char, unsigned char short, int, long, unsigned short, unsigned, unsigned long
Floating types The types that can be used to hold real values.
float, double, long double
12
Characters and the data Type char
Characters: Each char is stored in one byte of memory Variables of any integral type can be used
to represent characters.char, int
When a variable is used to read in characters and a test must be must be made for EOF, The variable should be of type int, not
char
13
Characters and the data Type char
Exampleschar c=‘a’; /* ‘a’ has ASCII encoding 97 */int i=65; /* 65 is SCII encoding for ‘A’ */
printf(“%c”, c+1);/* b is printed */
printf(“%d”, c+2);/* 99 is printed */
printf(“%c”, i+3);/* D is printed */
Character codes for letters A through Z are contiguousCharacter codes for letters a through z are contiguous
14
Characters and the data Type char
char, signed char, and unsigned char Each of the three char types is stored in one
byes, which can hold 28=256 distinct values.signed char : -128 to 127unsigned char : 0 to 255
Typically, char is equivalent to either signed char or unsigned char, depending on the compiler.
15
Characters and the data Type char
Summary: Each char is stored in one byte of memory Variables of any integral type can be used to represent
characters. When a variable is used to read in characters and a test
must be must be made for EOF, The variable should be of type int, not chars
Each of the three char types is stored in one byes, which can hold 256 distinct values.signed char : -128 to 127unsigned char: 0 to 255char is equivalent to either signed char or unsigned
char, depending on the compiler.
16
The Fundamental Data Types
Integral types The types that can be used to hold integer
values.Characters: char, signed char, unsigned char short, int, long, unsigned short, unsigned, unsigned long
Floating types The types that can be used to hold real values.
float, double, long double
17
The Data Type int and the integral types
int Typically, an int is stored in a machine word. The length of a machine word is system-
dependentTwo bytes: 16 bits
o -215, -215+1, ……, -3, -2, -1, 0, 1, 2, 3, ……, 215-1
Four bytes: 32 bitso -231, -231+1, ……, -3, -2, -1, 0, 1, 2, 3, ……, 231-1
Integer overflow
18
The Fundamental Data Types
Integral types The types that can be used to hold integer
values.Characters: char, signed char, unsigned char short, int, long, unsigned short, unsigned, unsigned long
Floating types The types that can be used to hold real values.
float, double, long double
19
The Data Type int and the integral types
short, int, long storage provided for each type:
short <= int <= longsigned/unsigned
The integer values stored in an unsigned variable have no sign.
Example, If a variable of type unsigned int is stored
in 4 bytes,o range: 0, 1, ……, 232-1 o Compared to int: -231, ……, -2, -1, 0, 1, 2, ……,
231-1
20
The Fundamental Data Types
Integral types The types that can be used to hold integer
values.Characters: char, signed char, unsigned char short, int, long, unsigned short, unsigned, unsigned long
Floating types The types that can be used to hold real values.
float, double, long double
21
The Floating Types
Three floating types: float, double and long double
float: a floating constant with suffix Fo Example: 3.7F
double: no suffix, o Example: 3.7
long double: a floating constant with suffix L
o Example: 3.7L
22
The Floating Types
Notation for floating constants: Decimal notation 12.0 Exponential notation:
Examples:o 1.2e5 = 1.2*105
o 1.2e-5 = 1.2*10-5
23
The Floating Types
rules of exponential notation: No blank, no special characters (such as , ; ) Three parts: Integer Fraction Exponent
must contain either a decimal point or an exponential part or both
If a decimal point is present, either an integer part or fractional part or both must be present.
Otherwise, there must be an integer part along with an exponential part.
Example: 1.234e-5
24
The Floating Types
Format of exponential notation: (cont’d) Example
3.13.1e-2F0e01.
But not3.1,131.e0-3.1 /* floating constant expression */
No blank, no special characters (such as , ; )either a decimal point or an exponential part or bothIf a decimal point is present, either an integer part or fractional part or both must be present.Otherwise, there must be an integer part along with an exponential part.
25
The Floating Types
Three floating types: float, double and long double storage : float <= double <= long double Not all real numbers are representable.
Typically, a float: 10-38 to 10+38
a double: 10-308 to 10+308
Floating arithmetic operations, unlike the integer arithmetic operations, need not be exact.
26
The Floating Types
Summary: Three floating types: float, double and long
doublestorage : float <= double <= long double
Notation of floating constant:Decimal notation: 123456.0Exponential notation: 1.23456e5
Not all real numbers are representable. Floating arithmetic operations, unlike the integer
arithmetic operations, need not be exact.
27
Outline
DeclarationsFundamental data types
Characters and the data type char The Data type int and the integral types The floating types
The sizeof OperatorMathematical FunctionsConversions and Casts
28
The sizeof Operator
Operator: sizeof(object) Returns an integer that represents the number
of bytes needed to store the object in memory. An object can be
a type o into float,
An expression o a+b,
An array or structure type (introduced later)
29
The sizeof Operator
Why Operator: sizeof(object)? The sizes of some fundamental types are
machine dependent, such as int. The sizeof operator provides precise
information about the store requirements for the fundamental types on a given machine.
30
The sizeof Operator
Example#include <stdio.h>int main(void){ printf("Size of char: %3d byte \n", sizeof(char)); printf("Size of int: %3d byte \n", sizeof(int)); printf("Size of float: %3d byte \n", sizeof(float)); printf("Size of double: %3d byte \n", sizeof(double));}
% a.outSize of char: 1 byteSize of int: 4 byteSize of float: 4 byteSize of double: 8 byte
31
The sizeof Operator
sizeof(….) is an operator, not a function If sizeof is being applied to a type,
parentheses are requiredExample: sizeof (int), but not
sizeof int Otherwise, parentheses are optional
Exampleo sizeof(a+b+7.7) sizeof a+b+7.7
32
The sizeof Operator
Summary sizeof(object) Returns an integer that represents the number of
bytes needed to store the object in memory. An object can be
a type such as int or float,An expression such as a+b,An array or structure type (introduced later)
sizeof(….) is an operator, not a function If sizeof is being applied to a type,
o Parentheses are requiredOtherwise, parentheses are optional
33
Outline
DeclarationsFundamental data types
Characters and the data type char The Data type int and the integral types The floating types
The sizeof OperatorMathematical FunctionsConversions and Casts
34
Mathematical Functions
C System The C language The preprocessor The compiler The library
Contains many useful functions, such as file handles and mathematical functions.
Other tools, such as editors and debuggers
35
Mathematical Functions
There are no built-in mathematical functions in C language
Functions are available in the mathematics library. Examples of mathematical functions:
sqrt(), pow(), exp(), log(), sin(), cos(), tan()
36
Mathematical Functions
How to use the functions in the mathematics library? Provide function prototypes in the code
The function prototypes of mathematics functions are provided in file math.h
#include <math.h> In traditional C systems, the mathematics
library is often considered to be separate,The –lm option may be needed to compile
gcc –lm f.c
37
Mathematical Functions
Example
#include <math.h>main(){ double x = 0.81; printf("%.2f\n", sqrt(x));}
% gcc -lm m.c% a.out0.90%
38
Mathematical Functions
Summary There are no built-in mathematical functions
in C language Functions are available in the mathematics
library. How to use the functions in the
mathematics library?In the code: #include <math.h>Compile: gcc –lm f.c
39
Outline
DeclarationsFundamental data types
Characters and the data type char The Data type int and the integral types The floating types
The sizeof OperatorMathematical FunctionsConversions and Casts
40
Conversions and Casts
An arithmetic expression has both a value and a type Example:
int x=1, y=2;The type of expression (x+y) is int
41
Conversions and Casts
Arithmetic conversions Arithmetic conversions can occur when the
operands of a binary operator are evaluated.
Example:int i, float f;expression i+f
o i is promoted to a float o The expression i+f as a whole has type float.
42
Conversions and Casts
Arithmetic conversions Why type of an expression?
#include <math.h>main(){ int i=2; float f = 3.0; printf("%.2f\n", i+f); printf("%d\n", i+f);}
% gcc con.c% a.out5.001075052544%
The type of an expression The rules for conversions when types of the constants, variables and function calls making up the expression have different types.
43
Conversions and Casts
The integral promotions A char or short, either signed or unsigned,
can be used in any expression where an int or unsigned int may be used.
If all the values of the original type can be represented by an int, the value is converted to an int;
Otherwise it is converted to an unsigned int.
(unsigned) char, (unsigned) short int, unsigned int
44
Conversions and Casts
The usual arithmetic conversions If either operand is of type long double,
the other operand is converted to long double.
Otherwise, if either operand is of type double,the other operand is converted to double.
Otherwise, if either operand is of type float,the other operand is converted to float.float double long double
45
Conversions and CastsThe usual arithmetic conversions (cont’d) Otherwise, all operands are of integral types
If either is of type unsigned long, the other unsigned long.
Otherwise if either long, the other unsigned,If a long can represent all the values of an
unsigned, then unsigned long.Otherwise, both unsigned long
Otherwise if either has type long, the other long
Otherwise if either has type unsigned, the other unsigned
Otherwise, both have type intshort int unsigned long unsigned long
46
Conversions and Casts
Cast operator: explicit conversions (type)
Example: int i(double) iCasts the value of i so the expression has
type doubleThe variable i itself remains unchanged.
47
Conversions and Casts
More Examples: (long)(‘A’+1.0) X=(float)((int)y+1) (double)(x=7)
But not (double) x=7
48
Conversions and Casts
Cast operator: unary operator The same precedence as other unary
operator Right-to-left associativity Example:
(float) i + 3 ((float) i) +3
49
Conversions and Casts
Summary An arithmetic expression has both a value
and a type Arithmetic conversions can occur when the
operands of a binary operator are evaluated.
Cast operator: explicit conversions(type)
50
Outline
DeclarationsFundamental data types
Characters and the data type char The Data type int and the integral types The floating types
The sizeof OperatorMathematical FunctionsConversions and Casts
51
End of Chapter 6: The Fundamental Data Type
Read 6.1 – 6.13
52
Review of Chapter 3
53
How true and false are implemented in C Representation of true and false
false: represented by any zero valueo int 0o floating 0.0o Null character ‘\0’o Null Pointer ( will be introduced in Chapter
8)
true: represented by any nonzero value
54
Relational, Equality, and Logical Operators
Relational Operators: < > <= >=Equality Operators: == !=Logical Operators: ! && ||conditional operator: expr1? expr2: expr3
Semantics:First, expr1 is evaluated. If it is nonzero (true), then expr2 is evaluated, and
this is the value of the conditional expression as a whole.
If expr1 is zero (false), then expr3 is evaluated, and this is the value of the conditional expression as a whole.
55
The if and if-else Statement
exp is enclosed by parentheses Where appropriate, compound statements
should be used to group a series of statements under the control of a single if expression
An if or if-else statement can be used as the statement part of another if or if-else statement.an else attaches to the nearest if.
if (expr) statement1
elsestatement2
if (expr) statement1
56
The switch Statement
General form:
switch ( switch_exp ){ case constant_exp1: statements;
break; // optional case constant_exp2 : statements;
break; // optional ... case constant_expn: statements;
break; // optional default:
statements; break;
}
//optional
57
The switch Statement
The effect of a switch: Evaluate the switch_exp. Go to the case label having a constant value
that matches the value of the switch_exp.If a match is not found, go to the default
label. If there is no default label, terminate the
switch. Terminate the switch when a break
statement is encountered, or by “falling off the end”.
58
The switch Statement
switch ( switch_exp ){ case constant_exp1: statements;
break; // optional case constant_exp2 : statements; case constant_exp3 : statements; …../* no break */case constant_expi : statements;
break;……case constant_expn: statements;
break; // optional ……}Next statement;
59
The switch Statement
switch ( switch_exp ){ case constant_exp1: statements;
break; // optional ……case constant_expi : statements;
break;……case constant_expn: statements;
break; // optional default:
statements; break;
}Next statement;
60
The switch Statement
switch ( switch_exp ){ case constant_exp1: statements;
break; // optional ……case constant_expi : statements;
break;……case constant_expn: statements;
break; // optional }Next statement;
61
The while Statement
General formwhile (expr)
StatementNext statement
First expr is evaluated. If expr is nonzero (true), then statement is
executed and control is passed back to the beginning of the while loop. Statement is repeatedly until expr is zero
(false) Then control passes to next statement.
62
The for Statement
Semantics: First expr1 is evaluated. Then expr2 is evaluated.
If expr2 is nonzero (true), o then statement is executed,o expr3 is evaluatedo control passes back to the beginning of the for
loop again, except that evaluation of expr1 is skipped.
The process continues until expr2 is zero (false), at which point control passes to next statement.
for(expr1; expr2; expr3){
statement
} next statement
63
The for Statement
for (expr1; expr2; expr3) Any of all of the expressions in a for statement
can be missing, but the two semicolons must remain.If expr1 is missing, no initialization step is
performed as part of the for loopWhen expr2 is mission, the rule is that the
test is always true.
for (expr1; expr2; expr3)statement
Next statement
64
The do Statement
Semantics First statement is executed, and expr is
evaluated. If the value of expr is nonzero (true),
then control passes back to the beginning of the do statement, and process repeats itself.
When expr is zero (false), then control passes to next statement
do
statementwhile (expr);Next statement
65
The Break and Continue Statements
break statement An exit from the innermost enclosing
loop (such as a while loop) statement or switch statement
continue statement Causes the current iteration of a loop to
stop and the next iteration to begin immediately.
66
Review of Chapter 4
67
Outline of Chapter 4
How to write a function? Function Invocation Function Definition The return Statement Function Prototypes
More about function Program Correctness: The assert() Macro Function Declarations from the Compiler’s Viewpoint Invocation and Call-by-Value Developing a Large Problem
68
How to write a function?
#include <stdio.h>void prn_message(void);void prn_message(void);int main(void){ prn_message();prn_message(); printf(“Back to main function\n”); return 0;}void prn_message(void)void prn_message(void){{ printf(“A message for you: “);printf(“A message for you: “); printf(“Have a nice day!\n”);printf(“Have a nice day!\n”); return;return;}}
How to give the compiler information about the function?
Function prototype:How to pass control to the function?
Function InvocationHow to specify the function?
Function DefinitionHow to get the control back?
return statement
69
How to write a function?Preprocessing directivesfunction prototype of fucntion1function prototype of fucntion2int main(void){ Body of function definition}Header of function1 definition{
Body of function definition}Header of function2 definition{
Body of function definition}
function invocations
70
Program Correctness: The assert() Macro
C provides the assert() macro in assert.h to guarantee certain conditions assert(exp)
ensures the value of exp is trueif exp is false, the system prints out a
message and abort the program.
71
Function Declarations from the Compiler’s Viewpoint
Preprocessing directivesfunction prototype of fucntion 1function prototype of fucntion 1int main(void){ Body of function definition}Header of function1 definition{
Body of function definition}Header of function1 definition{
Body of function definition}
Preprocessing directivesHeader of function1 definition{
Body of function definition}Header of function1 definition{
Body of function definition}int main(void){ Body of function definition}
Give either the function definition or the function prototype or both before a function is used
72
Invocation and Call-by-Value
Function Invocation
fun_name(exp1, exp2); All arguments are passed call-by-value
Each argument is evaluated, and its value is used locally in place of the corresponding formal parameter.
If a variable is passed to a function, the stored value of that variable in the calling environment is not changed.
73
#include <stdio.h>int min2(int a, int b);int min3(int a, int b, int c);
min.h
#include “min.h”int main(void){ printf("%d\n", min3(1,3,4) ); return 0;}
main.c
int min2(int a, int b){ if (a<b) return a; else return b;}int min3(int a, int b, int c){ int mofab = min2(a,b); return min2(mofab, c);}
min.c
f.h: function prototypesf1.c, f2.c, f3.c
function definitions
in each .c file#include “f.h”
gcc f1.c f2.c f3.c
gcc main.c min.c
Developing a Large Problem