ICP Lecture 7: Syed Nasir Mehdi Nasirsmehdi@ciitsahiwal - Edu.pk
ICP Lecture 7: Syed Nasir Mehdi Nasirsmehdi@ciitsahiwal - Edu.pk
int main()
{
cout << value; // ERROR! value not defined yet!
int value = 100;
return 0;
}
Type Conversion
• When an operator’s operands are of different
data types, C++ will automatically convert
them to the same data type. This can affect
the results of mathematical expressions.
• Just like officers in the military, data types are
ranked. One data type outranks another if it
can hold a larger number. For example, a float
outranks an int.
Type Conversion
Data type ranking
• long double
• double
• float
• unsigned long
• long
• unsigned int
• int
Type conversion
• Rule 1: chars, shorts, and unsigned shorts are automatically promoted to int.
• Rule 2: When an operator works with two values of different data types, the lower
ranking value is promoted to the type of the higher-ranking value.
• In the following expression, assume that years is an int and interestRate is a float:
years * interestRate
• In the following statement, assume that area is a long int, while length and width
are both ints:
• area = length * width;
• Rule 3: When the final value of an expression is assigned to a variable, it will be
converted to the data type of that variable
• In the following statement, assume that area is a long int, while length and width
are both ints:
• area = length * width;
• Since length and width are both ints, they will not be converted to any other data
type. The
• result of the multiplication, however, will be converted to long so it can be stored
in area.
Type conversion
• int x, y = 4;
• float z = 2.7;
• x = y * z;
Type conversion
Integer Division
• When you divide an integer by another
integer in C++, the result is always an integer
double parts;
parts = 15 / 6;
• It doesn’t matter that parts is declared as a
double because the fractional part of the
result is discarded before the assignment
takes place.
Overflow and underflow
• When a variable is assigned a value that is too large or too small in range for that variable’s data
type, the variable overflows or underflows
• int main()
• int main()
{
// testVar is initialized with the maximum value for a short.
short testVar = 32767;
// Display testVar.
cout << testVar << endl;
testVar = testVar - 1;
cout << testVar << endl;
return 0;
}
Type Casting
• Type casting allows you to perform manual
data type conversion.