Download presentation
Presentation is loading. Please wait.
Published byChristopher Booth Modified over 9 years ago
1
Chapter 3 The Basic Data Types C/C++ Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
2
2 Basic Data Types When defining a variable you MUST specify what type data it contains. In C/C++ there are seven basic data types: character ( char ) character ( char ) wide character ( wchar_t ) wide character ( wchar_t ) integer ( int ) integer ( int ) floating point ( float ) floating point ( float ) double floating point ( double ) double floating point ( double ) Boolean ( bool ) Boolean ( bool ) valueless ( void ) valueless ( void )
3
3 Basic Data Types (continued) Data Type Memory Range char 8 bits-128 to 127 wchar_t16 bits0 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 float32 bits3.4E -38 to 3.4E +38 double64 bits1.7E –308 to 1.7E +308 boolN/Atrue or false voidN/Avalueless
4
4 Variables 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.
5
5 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;
6
6 Variable Declarations (continued) The type must be a valid data type, and variable_list may contain one or more identifier names separated by commas. Here are some examples: The variable name has nothing to do with its type. int i, j, k; char ch, chr; float f, balance; double d; bool hourly; double YearToDateSales; int Day_Of_Year;
7
7 Variable Declarations (continued) There are three places a variable may be declared: Inside functions (local variables) Inside functions (local variables) In the definition of function parameters (formal parameters) In the definition of function parameters (formal parameters) Outside of all functions ( global variables ) Outside of all functions ( global variables )
8
8 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;// displays 10 return 0; } void func() { // local to func() int x; x = -199; cout << x; // displays -199 }
9
9 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. We will stick to the term local variables.
10
10 Formal Parameters A function may have a parameter-list in which you define a function’s parameters. These are called formal parameters. int func1( 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.
11
11 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.
12
12 void func1(); // prototype for func1() void func2(); // prototype for func2() 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; func1(); } return 0; } void func1() { cout << “count: “ << count << end; // access global variable func2(); } void func2() { int count; // this is a local variable for( count = 0; count < 3; count++ ) cout << “.“; }
13
13 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: signed (the default for integers and char) signed (the default for integers and char) unsigned unsigned long long short 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.
14
14 Data Type Memory Range char 8 bits-128 to 127 unsigned char 8 bits0 to 255 signed char 8 bits-128 to 127 int 32 bits-2,147,483,648 to 2,147,483,647 unsigned int 32 bits0 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 bits0 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 bits0 to 4,294,967,295 signed long int 32 bits-2,147,483,648 to 2,147,483,647 float 32 bits3.4E-38 to 3.4E+38 double 64 bits1.7E-308 to 1.7E+308 long double 80 bits3.4E-4932 to 1.1E+4932 bool N/Atrue or false wchar_t 16 bits0 to 65,535
15
15 Sample Program int main() { short int i; // a signed short integer short unsigned int j; // 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.
16
16 Type Modifiers (continued) A shorthand notation is allowed unsigned, short, and long integers. Each of these are equivalent: short int x; short x; short int x; short x; unsigned short int y; unsigned short y; unsigned short int y; unsigned short y; long int a; long a; long int a; long a; unsigned long int b; unsigned long b; unsigned long int b; unsigned long b; unsigned int c; unsigned c; unsigned int c; unsigned c;
17
17 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; }
18
18 Literals Literals ( also called constants ) refer 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 TypeExamples of Literals int1 123 21000 -234 long int35000L -34L unsigned int10000U 987U 40000U unsigned long12323UL 900000UL float123.23F 4.3e-3F double23.23 123123.33 -0.9876324 long double1001.2L
19
19 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. Hexadecimal format: 0x6D or 0XFF or 0X1B6C Hexadecimal format: 0x6D or 0XFF or 0X1B6C Octal format………: 012 or 057 Octal format………: 012 or 057 Hexadecimal literals have a prefix of 0x or 0X followed by a hexadecimal number ( 0123456789ABCDEF ). Octal literals have a prefix of a 0 followed by an octal number ( 01234567 ).
20
20 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 Example: “ABCDEF ” – generates A char literal is enclosed by single quotes ( ‘’ ) and generate only one byte of memory. Example: ’A’ – generates A ABCDEF\0 A
21
21 Character Escape Sequences There are a few escape sequence characters that you can use with cout. Note the lower case letters. \aAlarm (beeps the speaker). \aAlarm (beeps the speaker). \bBackspace. \bBackspace. \nNew line. \nNew line. \tHorizontal tab. \tHorizontal tab. \fForm Feed \fForm Feed \rCarriage Return \rCarriage Return \vVertical Tab \vVertical Tab \\Backslash \\Backslash \?Question Mark \?Question Mark \’Single Quote \’Single Quote \”Double Quote \”Double Quote \NOctal constant (N = octal constant) \NOctal constant (N = octal constant) \xN Hexadecimal constant (N = hex constant) \xN Hexadecimal constant (N = hex constant)
22
22 Character Escape Sequences Examples: cout << ‘\a’; cout << “ABC\bDEF”; “C:\ABC\XYZ\DATAFILE.TXT” “C:\\ABC\\XYZ\\DATAFILE.TXT” cout << “Hello World\n”; cout << “\tHello World\n”; cout << “He said \”Hi\”.”;
23
23 Variable Initializations As mentioned earlier you can give a variable an initial value when it is declared. The format is: type variable-name = value; type variable-name = value;Examples: char ch = ‘a’; int first = 0; float balance = 123.23F; double amount = 0.0; int second = first; int x = 5, y, z = 20;
24
24 Variable Initializations Notes: Global variables are initialized only at the start of the program. Global variables are initialized only at the start of the program. Local variables are initialized each time the function they are declared in is entered. Local variables are initialized each time the function they are declared in is entered. All global variables are initialized to zero if no other initializer is specified. All global variables are initialized to zero if no other initializer is specified. Local variables that are not initialized will have unknown values (garbage). Local variables that are not initialized will have unknown values (garbage).
25
25 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: Arithmetic Arithmetic Relational Relational Logical Logical Bitwise Bitwise There are other special ones that perform particular tasks: -> & * ? -> & * ?
26
26 Arithmetic Operators OperatorAction + Addition - Subtraction, also unary minus * Multiplication / Division % Remainder or Modulus -- Decrement ++ Increment
27
27 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.
28
28 Data Type of an Expression The data type of an expression depends on the type of its operands. The data type of an expression depends on the type of its operands. Examples: Examples: int X = 5; int X = 5; int Y = 10; X + Y int Y = 10; X + Y The result is of type int if both operands are int’s. The result is of type int if both operands are int’s. int X = 5; double Y = 10.5; int X = 5; double Y = 10.5; X + Y X + Y The result is a double when one operand is a type int and the other operand is a type double. The result is a double when one operand is a type int and the other operand is a type double.
29
29 Data Type of an Expression 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. 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. Example: Example: int X = 5; int Y = 10; double A; A = Y / X; The expression Y / X evaluates to an integer. This value is converted to type double before it is stored in A. The expression Y / X evaluates to an integer. This value is converted to type double before it is stored in A. If the data types were reversed the fractional part of the expression would be lost in the conversion. If the data types were reversed the fractional part of the expression would be lost in the conversion.
30
30 Evaluating Expressions Rules for evaluating expressions: Rules for evaluating expressions: All expressions in parentheses must be evaluated separately. Nested parenthesized expressions must be evaluated from the inside out, with the innermost expression evaluated first. 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: Operators in the same expression are evaluated in the following order: Unary +, - Unary +, - *, /, % *, /, % Binary +, - 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. 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.
31
31 Compound Assignment Assignments that use the old value of a variable to compute its new value are commonly used in C programs. Assignments that use the old value of a variable to compute its new value are commonly used in C programs. Example: Counter = Counter + 1; Example: Counter = Counter + 1; C’s compound assignment operators allow us to shorten this statement. C’s compound assignment operators allow us to shorten this statement. The general syntax is: variable operator value; The general syntax is: variable operator value; The operators can be: The operators can be: += Adds the value to the variable. += Adds the value to the variable. -= Subtracts the value to the variable. -= Subtracts the value to the variable. *= Multiplies the value with the variable. *= Multiplies the value with the variable. /= Divides the value to the variable. /= Divides the value to the variable. %= Computes the remainder when the variable is divided by the value, the result is then stored in the variable. %= Computes the remainder when the variable is divided by the value, the result is then stored in the variable.
32
32 Increment and Decrement Operators The counting loops that you have seen have all included assignment expressions in the form of: The counting loops that you have seen have all included assignment expressions in the form of: Counter = counter + 1; Counter = counter + 1; Counter += 1; Counter += 1; The increment and decrement operators are: The increment and decrement operators are: ++ Increment ++ Increment -- Decrement -- Decrement The increment and decrement operators take a single variable as their operand. The increment and decrement operators take a single variable as their operand.
33
33 Increment and Decrement Operators The ++ operator increments its operand by the value of 1. The ++ operator increments its operand by the value of 1. The -- operator decrements its operand by the value of 1. The -- operator decrements its operand by the value of 1. Examples: ++counter; or counter++; --counter; or counter--; Examples: ++counter; or counter++; --counter; or counter--; The value of the expression in which the ++ or -- operator is used depends on the position of the operator. The value of the expression in which the ++ or -- operator is used depends on the position of the operator.
34
34 Post verses Pre Increment and Decrement Operators When the ++ is placed immediately in front of its operand (prefix increment), the value of the variable is increased by 1 before the variable is used in any expression. When the ++ is placed immediately in front of its operand (prefix increment), the value of the variable is increased by 1 before the variable is used in any expression. When the ++ is placed immediately after its operand (postfix increment), the value of the variable is increased by 1 after the variable is used in any expression. When the ++ is placed immediately after its operand (postfix increment), the value of the variable is increased by 1 after the variable is used in any expression.
35
35 Post verses Pre Increment and Decrement Operators Examples: int x = 0; int y = 1; cout << x++; // displays 0 x = 0; cout << ++x; // displays 1
36
36 Precedence of Arithmetic Operators Highest ++ -- - (unary minus) * / % Lowest + -
37
37 Relational and Logical Operators Relational refers to relationship that values have with one another. Relational refers to relationship that values have with one another. Logical refers to the ways in which true and false values may be connected together. Logical refers to the ways in which true and false values may be connected together. 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). 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). Any non-zero value is considered true in C/C++. Any non-zero value is considered true in C/C++.
38
38 Relational and Logical Operators OperatorMeaning > Greater than >= Greater than or equal to < Less than <= Less than or equal to == Equal to != Not equal to Relational Operators: OperatorMeaning && AND || OR ! NOT Logical Operators:
39
39 Truth Table for Logical Operators pqp AND qp OR qNOT p 0 0001 0 1011 1 1110 1 0010
40
40 Precedence of Relational and Logical Operators Highest ! > >= < <= == != && Lowest ||
41
41 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.
42
42 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 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.
43
43 Expressions and Type Conversions If the type of either operand is a floating-point type: long double 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.
44
44 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; // c is converted to int f = i; // i is converted to float d = f; // f is converted to double
45
45 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 is now 842 i = -842.97; // i is now –842
46
46 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 // *** wrong *** i = 1.0e20;// *** wrong *** f = 1.0e100// *** wrong ***
47
47 Converting to and from bool Values of type bool are 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 false and a non-zero value becomes true.
48
48 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. int x; int x; (float) x / 2 (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.
49
49 Casts (continued) Examples: float f = 45.678, frac-part; float f = 45.678, frac-part; frac-part = (int)f; // frac-part = 45 frac-part = (int)f; // frac-part = 45 float quotient; float quotient; int dividend = 7, divisor = 3; int dividend = 7, divisor = 3; quotient = dividend / divisor; // result 2 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; quotient = (float)dividend / divisor;
50
50 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); // not very readable x = 10 / y * (127 / x); // much better 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; x = (y / 3) – (34 * temp) + 127; x = (y / 3) – (34 * temp) + 127;
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.