2c3f7b71016626bd245b73d47a2b43a8.ppt
- Количество слайдов: 50
Chapter 3 The Basic Data Types C/C++ Programming © 2003 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Basic Data Types When defining a variable you MUST specify what type data it contains. In C/C++ there are seven basic data types: n character ( char ) n n n wide character ( wchar_t ) integer ( int ) floating point ( float ) double floating point ( double ) Boolean ( bool ) valueless ( void ) 2
Basic Data Types (continued) Data Type char Memory Range 8 bits -128 to 127 wchar_t 16 bits 0 to 65, 535 int (16 bit) 16 bits -32, 768 to 32, 767 int (32 bit) 32 bits -2, 147, 483, 648 to 2, 147, 483, 647 float 32 bits 3. 4 E -38 to 3. 4 E +38 double 64 bits 1. 7 E – 308 to 1. 7 E +308 bool N/A true or false void N/A valueless 3
Variables are used to store data temporarily in your program. When you create a variable your program, underneath the hood, allocates memory from the operating system for the value you want to store. Each time you create a variable you will have to define the type of data that it will be storing. We define the data type because the operating system needs to know how much memory to allocate for the values you will be storing. 4
Variable Declarations The variable declaration in a program communicates to the compiler the names of all variables used in a program. They also tell the compiler what kind of information will be stored in each variable. You are required you declare every variable used in a program. The general syntax is: type variable_list; 5
Variable Declarations (continued) The typemust be a valid data type, and variable_list may contain one or more identifier names separated by commas. Here are some examples: int i, j, k; char ch, chr; float f, balance; double d; bool hourly; double Year. To. Date. Sales; int Day_Of_Year; The variable name has nothing to do with its type. 6
Variable Declarations (continued) There are three places a variable may be declared: n Inside functions (local variables) n In the definition of function parameters (formal parameters) n Outside of all functions ( global variables ) 7
Local Variables Local variables are declared inside functions. They can only be used inside the function they are declared in and do not exist outside that function. void func(); // prototype for func() int main() { int x; // local to main() x = 10; func(); cout << “n“; cout << x; return 0; // displays 10 } void func() { int x; x = -199; cout << x; } // local to func() // displays -199 8
Local Variables (continued) Local variables are created when the function is called and destroyed when the function terminates. The memory needed for local variables is created and destroyed in the same way. Local variables DO NOT retain their values between function calls. Some books call local variables dynamic variables or automatic variables will stick to the term local variables. We. 9
Formal Parameters A function may have a parameter-list which you define a in function’s parameters. These are called formal parameters. int func 1( int first, int last, char ch ) {. . . } This function has three parameters that will contain data passed to the function when it is called. They can be used/modified by the function just like local variables. Like local variables, their contents is lost when the function terminates. 10
Global Variables Global variables and their contents stay in existence throughout the entire execution of the program. Global variables are declared outside of functions. Normally they are place at the top of the program before the function main(). They can be accessed by any function in the program. 11
void func 1(); void func 2(); // prototype for func 1() // prototype for func 2() int count; // this is a global variable int main() { int i; // this is a local variable for( i = 0; i < 10; i++ ) { count = i * 2; func 1(); } return 0; } void func 1() { cout << “count: “ << count << end; func 2(); } // access global variable void func 2() { int count; // this is a local variable for( count = 0; count < 3; count++ ) cout << “. “; } 12
Some Type Modifiers The char, int, and double data types are allowed to have modifiers preceding them. A modifier allows you to alter the meaning of the base type. These modifiers are: n n signed (the default for integers and char) unsigned long short All can be applied to the integer base types. signed and unsigned can be applied to the char type, and long can be applied to the double type. 13
Data Type Memory Range char 8 bits -128 to 127 unsigned char 8 bits 0 to 255 signed char 8 bits -128 to 127 int 32 bits -2, 147, 483, 648 to 2, 147, 483, 647 unsigned int 32 bits 0 to 4, 294, 967, 295 signed int 32 bits -2, 147, 483, 648 to 2, 147, 483, 647 short int 16 bits -32, 768 to 32, 767 unsigned short int 16 bits 0 to 65, 535 signed short int 16 bits -32, 768 to 32, 767 long int 32 bits -2, 147, 483, 648 to 2, 147, 483, 647 unsigned long int 32 bits 0 to 4, 294, 967, 295 signed long int 32 bits -2, 147, 483, 648 to 2, 147, 483, 647 float 32 bits 3. 4 E-38 to 3. 4 E+38 double 64 bits 1. 7 E-308 to 1. 7 E+308 long double 80 bits 3. 4 E-4932 to 1. 1 E+4932 bool wchar_t N/A 16 bits true or false 0 to 65, 535 14
Sample Program int main() { short int i; short unsigned int j; // a signed short integer // an unsigned short integer j = 60000; I = j; cout << I << “ “ << j << endl; return 0; } Output: -5536 60000 The value 60000 exceeds the capacity of a short integer and gets interpreted as the value -5536. 15
Type Modifiers (continued) A shorthand notation is allowed unsigned, short, and long integers. Each of these are equivalent: n short int x; n unsigned short int y; n long int a; n unsigned long int b; n unsigned int c; short x; unsigned long a; unsigned short y; long b; c; 16
char Types A variable of the type char ( char ch; ) can store ONLY half of the 256 character ASCII character set. If you need the capability of representing ALL the characters of the ASCII character set you must define it as being unsigned ( unsigned char ch; ). A char type can also hold numeric values equivalent to a “small” integer with a range of from -128 to +127. For example: int main() { char letter; for( letter = ‘Z’; letter >= ‘A’; letter-- ) cout << letter << endl; return 0; } 17
Literals ( also called constantsrefer to fixed values that cannot be ) changed by the program. They can be of any of the basic data types. How they are represented determines their specific data type. Here is a summary: Data Type Examples of Literals int 1 123 21000 long int 35000 L -34 L unsigned int 10000 U 987 U unsigned long 12323 UL 900000 UL float 123. 23 F 4. 3 e-3 F double 23. 23 long double 1001. 2 L 123123. 33 -234 40000 U -0. 9876324 18
Hexadecimal and Octal Literals You can also create literals that represent both octal ( base 8 ) and hexadecimal ( base 16 ) numbers. Hexadecimal literals are by far more common than octal values. n Hexadecimal format: 0 x 6 D or 0 XFF or 0 X 1 B 6 C n Octal format………: 012 or 057 Hexadecimal literals have a prefix of 0 x or 0 X followed by a hexadecimal number ( 0123456789 ABCDEF). Octal literals have a prefix of a 0 followed by an octal number (01234567). 19
String and char Literals A string is a set of characters enclosed by double quotes ( “” ). For example, “This is a string literal” is an example of a string literal. Remember that C does not have a a built in string data type. C uses null terminates character arrays to house strings. Example: “A” – generates A Example: “ABCDEF” – generates A B C D E F A char literal is enclosed by single quotes ( ‘’) and generate only one byte of memory. Example: ’A’ – generates A 20
Character Escape Sequences There a few escape sequence characters that you can use with cout. Note the lower case letters. n n n n a speaker). b n t f r v \ ? ’ ” N (N = octal constant) x. N Hexadecimal constant (N Alarm (beeps the Backspace. New line. Horizontal tab. Form Feed Carriage Return Vertical Tab Backslash Question Mark Single Quote Double Quote Octal constant = hex constant) 21
Character Escape Sequences Examples: cout << ‘a’; cout << “ABCb. DEF”; “C: ABCXYZDATAFILE. TXT” “C: \ABC\XYZ\DATAFILE. TXT” cout << “Hello Worldn”; cout << “t. Hello Worldn”; cout << “He said ”Hi”. ”; 22
Variable Initializations As mentioned earlier you can give a variable an initial value when it is declared. The format is: type variable-name = value; Examples: char ch = ‘a’; int first = 0; float balance = 123. 23 F; double amount = 0. 0; int second = first; int x = 5, y, z = 20; 23
Variable Initializations Notes: n Global variables are initialized only at the start of the program. n Local variables are initialized each time the function they are declared in is entered. n All global variables are initialized to zero if no other initializer is specified. n Local variables that are not initialized will have unknown values (garbage). 24
Operators C/C++ have MANY built-in operators. An operator is a symbol that tells the compiler to perform a specific mathematical or logical operations. The general classes of operators are: n Arithmetic n Relational n Logical n Bitwise There are other special ones that perform particular tasks: -> & * ? 25
Arithmetic Operators Operator + * / % -++ Action Addition Subtraction, also unary minus Multiplication Division Remainder or Modulus Decrement Increment 26
Arithmetic Expressions The operators +, -, *, and / may be used with type int or double operands. The data type of the result is the same as the data types of the operands. The remainder operator ( % ) can be used with integer operands to find the remainder of longhand division. When applied to two positive integers, the division operator ( / ) computes the integral part of the result of dividing its first operand by its second. The division operator is undefined when the divisor is 0. 27
Data Type of an Expression n n The data type of an expression depends on the type of its operands. Examples: int X = 5; int Y = 10; X + Y n The result is of type int if both operands are int’s. int X = 5; double Y = 10. 5; X + Y 28
Data Type of an Expression n The expression is evaluated before the assignment is made, and the type of the variable being assigned has no effect whatsoever on the expression value. n Example: int X = 5; int Y = 10; double A; 29
Evaluating Expressions n Rules for evaluating expressions: n n n All expressions in parentheses must be evaluated separately. Nested parenthesized expressions must be evaluated from the inside out, with the innermost expression evaluated first. Operators in the same expression are evaluated in the following order: n Unary +, n *, /, % n Binary +, Unary operators in the same sub expression and at the same precedence level are evaluated right to left. Binary operators in the same sub expression at the same precedence level are evaluated left to right. 30
Compound Assignment n Assignments that use the old value of a variable to compute its new value are commonly used in C programs. n Example: n C’s compound assignment operators allow us to shorten this statement. n The general syntax is: value; n The operators can be: n += Adds the value to the variable. n -= Subtracts the value to the variable. n *= Multiplies the value with the variable. n /= Divides the value to the variable. n %= Computes the remainder when the variable is divided 31 by the value, the result is then stored in the variable. Counter = Counter + 1; variable operator
Increment and Decrement Operators n n n The counting loops that you have seen have all included assignment expressions in the form of: n Counter = counter + 1; n Counter += 1; The increment and decrement operators are: n ++ Increment n -Decrement The increment and decrement operators take a single variable as their operand. 32
Increment and Decrement Operators n The ++ operator increments its operand by the value of 1. n The -- operator decrements its operand by the value of 1. n Examples: n The value of the expression in which the ++ or -operator is used depends on the position of the operator. ++counter; or counter++; --counter; or counter--; 33
Post verses Pre Increment and Decrement Operators n When the ++ is placed immediately in front of its operand (prefix increment value of the variable is ), the increased by 1 before the variable is used in any expression. n When the ++ is placed immediately after its operand (postfix increment value of the variable is increased by ), the 1 after the variable is used in any expression. 34
Post verses Pre Increment and Decrement Operators Examples: int x = 0; int y = 1; cout << x++; x = 0; cout << ++x; // displays 0 // displays 1 35
Precedence of Arithmetic Operators Highest Lowest ++ -- (unary minus) * / % + - 36
Relational and Logical Operators n Relational refers to relationship that values have with one another. n Logical refers to the ways in which true and false values may be connected together. n The outcome of a relational or logical operation is a bool , which can be either true (automatically converted to the value 1) or false (automatically converted to the value 0). n Any non-zero value is considered true in C/C++. 37
Relational and Logical Operators Relational Operators: Operator Meaning > Greater than >= Greater than or equal to < Less than <= Less than or equal to == Equal to != Not equal to Logical Operators: Operator Meaning && AND || OR ! NOT 38
Truth Table for Logical Operators p q p AND q p OR q NOT p 0 0 1 0 1 1 1 0 1 0 39
Precedence of Relational and Logical Operators Highest Lowest ! > == && || >= != < <= 40
Expressions and Type Conversions Operators, literals, and variables are constituents of expressions. When literals and variables of different types mixed in an expression, they are converted to the same type. 1. Integral promotion - First, all char and short int values are automatically elevated to int. 2. Type promotion – Second, all operands are converted “up” to the type of the largest operand. This is done on a operation-by-operation basis. 41
Expressions and Type Conversions These conversions apply to the operands of most binary operators, including arithmetic, relational, and equality operators. If neither operand type is a floating-point type: long int Note: When a long int and an unsigned int have the same length and one operand is a long int and the other an unsigned int, both are converted to an unsigned long int. 42
Expressions and Type Conversions If the type of either operand is a floating-point type: long double float It is legal to convert a char to a double or an int to a float. Once a conversion has been applied, each pair of operands will be of the same type, and the result of each operations will be the same as the type of both operands. 43
Conversion During Assignment C/C++ follows the simple rule that the expression on the right sight of the assignment is converted to the type of the variable on the left side. char c; int i; float f; double d; i = c; f = i; d = f; // c is converted to int // i is converted to float // f is converted to double 44
Conversion During Assignment Assigning a floating-point number to an integer variable drops the fractional part of the number: int i; i = 842. 97; i = -842. 97; // i is now 842 // i is now – 842 45
Conversion During Assignment Assigning a value to a variable of a narrower type will give a meaningless result (or worse) if the value is outside the range of the variable's type (the compiler usually gives a warning message): char c; int i; float f; c = 10000 i = 1. 0 e 20; f = 1. 0 e 100 // *** wrong *** 46
Converting to and from bool Values of type boolare automatically converted into the integers 0 or 1 when used in an integer expression. When an integer result is converted to type bool 0 becomes , falseand a non-zero value becomes true. 47
Casts A cast allows you to force an expression to be of a specific type. Format: (type-name) expression type-name is the type to which the expression is to be converted. For example, the following expression forces its result to be a float instead of an int x; (float) x / 2 Casts are often considered operators. As an operator, a cast is unary and has the same precedence as any other unary operator. 48
Casts (continued) Examples: float f = 45. 678, frac-part; frac-part = (int)f; // frac-part = 45 float quotient; int dividend = 7, divisor = 3; quotient = dividend / divisor; // result 2 Since dividend and divisor are int's above, quotient will contain only the whole number portion ( 2 ) and no decimal places. The solution is below: quotient = (float)dividend / divisor; 49
Spacing and Parentheses Expressions may have spaces and tabs to enhance readability, for example: x=10/y*(127/x); // not very readable x = 10 / y * (127 / x); // much better Redundant or additional parentheses will not cause errors or slow execution of the expression. You are encouraged to use parentheses to make clear the exact order of an expression’s evaluation. Which as these is easier to read? x = y/3 -34*temp+127; x = (y / 3) – (34 * temp) + 127; 50
2c3f7b71016626bd245b73d47a2b43a8.ppt