Professional Documents
Culture Documents
Week 5
Week 5
Fundamentals
1
A CASE STUDY
General Crates, Inc. (GCI) builds custom-designed
wooden crates.
GCI can build wooden crates of any size
You have been asked to write a program that calculates
the:
Volume (in cubic feet)
Cost
Customer price
Profit of any crate GCI builds
Continued…
Continued…
THE PROGRAM
TYPE CONVERSION
6
WHEN YOU MIX APPLES WITH
ORANGES: TYPE CONVERSION
Operations are performed between operands of the same
type.
If not of the same type, C++ will convert one to be the type of
the other
This can impact the results of calculations.
C++ follows data type conversion rules when performing
mathematical operations on variables of different data types.
HIERARCHY OF TYPES
Highest:
long double
double
float
unsigned long
long
Lowest:
unsigned int
int
Ranked by largest number they can hold
TYPE COERCION
C++ strives to convert the operands of mathematical
operator to the same type if these are different.
Type Coercion: automatic conversion of an operand to
another data type
Promotion: convert to a higher type
Demotion: convert to a lower type
COERCION RULES
Rule#1
int yeares;
float interestRate;
..
Cout<<years * interestRate;
int x, y = 4;
long int area; float z = 2.7;
int length, width; x = y * z;
..
area = length * width; //In the expression y * z , y will be
promoted to float and 10.8 will result
//The result of the multiplication will be from the multiplication.
converted to long so it can be stored in
area . Since x is an integer, however, 10.8 will
be truncated and 10 will be stored in x .
OVERFLOW AND
UNDERFLOW
13
OVERFLOW AND UNDERFLOW
Occurs when assigning a value that is too large
(overflow) or too small (underflow) to be held in a
variable
a , b , and c are all short integers:
a = b * c;
If b and c are set to values large enough, the
multiplication will produce a number too big to be stored
in a called the overflow situation.
When an Integer overflow
• Typically, when an integer overflows, its contents
wrap around to that data type’s lowest possible value
& vice versa
17
TYPE CASTING
A type cast expression lets you manually promote or
demote a value i.e. do manual conversion
The general format of a type cast expression is