Introduction To Object-Oriented Programming COMP2011: C++ Basics II
Introduction To Object-Oriented Programming COMP2011: C++ Basics II
Object-Oriented Programming
int main()
{
cout << "sizeof(bool) = " << sizeof(bool) << endl;
cout << "sizeof(char) = " << sizeof(char) << endl;
cout << "sizeof(short) = " << sizeof(short) << endl;
cout << "sizeof(int) = " << sizeof(int) << endl;
cout << "sizeof(long) = " << sizeof(long) << endl;
cout << "sizeof(long long) = " << sizeof(long long) << endl;
cout << "sizeof(float) = " << sizeof(float) << endl;
cout << "sizeof(double) = " << sizeof(double) << endl;
cout << "sizeof(long double) = " << sizeof(long double) << endl;
return 0;
}
sizeof(bool) = 1 sizeof(bool) = 1
sizeof(char) = 1 sizeof(char) = 1
sizeof(short) = 2 sizeof(short) = 2
sizeof(int) = 4 sizeof(int) = 4
sizeof(long) = 4 sizeof(long) = 8
sizeof(long long) = 8 sizeof(long long) = 8
sizeof(float) = 4 sizeof(float) = 4
sizeof(double) = 8 sizeof(double) = 8
sizeof(long double) = 12 sizeof(long double) = 16
sign−bit
int main()
{
int HALF = 2; // Reduce the number by this factor
int count = 0; // Count how many times that x can be halved
float x; // Number to halve
return 0;
}
{horner, kccecia, lixin}@cse.ust.hk COMP2011 (Spring 2018) p.10
Example: Continuously Halving a float Number ..
int main()
{
int HALF = 2; // Reduce the number by this factor
int count = 0; // Count how many times that x can be halved
int x; // Number to halve
return 0;
}
{horner, kccecia, lixin}@cse.ust.hk COMP2011 (Spring 2018) p.12
Example: Continuously Halving an int Number ..
int main()
{
bool x = true;
bool y = false;
return 0;
}
int main()
{
char donor_blood_type, recipient_blood_type;
bool exact_match, match_all;
if (exact_match || match_all)
cout << "Great! A donor is found!" << endl;
else
cout << "Keep searching for the right donor." << endl;
return 0;
}
{horner, kccecia, lixin}@cse.ust.hk COMP2011 (Spring 2018) p.16
Underflow and Overflow in Integral Data Types
Analogy:
Blood Types
Receiver Donor
A A, O
B B, O
AB A, B, AB, O
O O
Examples
float x = 3.2; // Initialize x with 3.2 by assignment
double y = 5.7; // Initialize y with 5.7 by assignment
short k = x; // k = ?
int n;
n = y; // n = ?
Compiler Warnings
a.cpp:9: warning: converting to ‘short int’ from ‘float’
a.cpp:11: warning: converting to ‘int’ from ‘double’
int k = 5;
int n = 2;
float x = n/k; // What is the value of x?
int k = 5, n = 2;
float x = static_cast<double>(n)/k;
float y = n/static_cast<double>(k);
float z = static_cast<double>(n)/static_cast<double>(k);
Constants
Example
const char BACKSPACE = '\b';
const float US2HK = 7.80;
const float HK2RMB = 0.86;
const float US2RMB = US2HK * HK2RMB;
int main()
{
const int COMP2011_QUOTA = 320;
const float STUDENT_2_PROF_RATIO = 100.0;
const float STUDENT_2_TA_RATIO = 40.0;
const float STUDENT_2_ROOM_RATIO = 100.0;
return 0;
}
{horner, kccecia, lixin}@cse.ust.hk COMP2011 (Spring 2018) p.30