Data Types
Constants
Constants name values that should not change after they are initialized.
const
Use `const` for a value that should stay fixed.
Constants
constants.cpp
Replay: real traced execution (multi-file project)
#include <iostream>
int main() {
const int minutesPerHour = 60;
int hours = 2;
int totalMinutes = hours * minutesPerHour;
std::cout << "hours=" << hours << std::endl;
std::cout << "minutes=" << totalMinutes << std::endl;
return 0;
}
#include <iostream>
int main() {
const int minutesPerHour = 60;
int hours = 1;
int totalMinutes = hours * minutesPerHour;
std::cout << "hours=" << hours << std::endl;
std::cout << "minutes=" << totalMinutes << std::endl;
return 0;
}
#include <iostream>
int main() {
const int minutesPerHour = 60;
int hours = 4;
int totalMinutes = hours * minutesPerHour;
std::cout << "hours=" << hours << std::endl;
std::cout << "minutes=" << totalMinutes << std::endl;
return 0;
}
minutesPerHour ← 60, hours ← 2, totalMinutes ← 120
3int main() {4 const int minutesPerHour→ 60 = 60;5 int hours→ 2 = 2; //@hours=1, 46 int totalMinutes→ 120 = hours2 * minutesPerHour60;78 std::cout << "hours=" << hours2 << std::endl;9 std::cout << "minutes=" << totalMinutes120 << std::endl;10 return 0;11}outputhours=2 minutes=120
minutesPerHour ← 60, hours ← 1, totalMinutes ← 60
3int main() {4 const int minutesPerHour→ 60 = 60;5 int hours→ 1 = 1;6 int totalMinutes→ 60 = hours1 * minutesPerHour60;78 std::cout << "hours=" << hours1 << std::endl;9 std::cout << "minutes=" << totalMinutes60 << std::endl;10 return 0;11}outputhours=1 minutes=60
minutesPerHour ← 60, hours ← 4, totalMinutes ← 240
3int main() {4 const int minutesPerHour→ 60 = 60;5 int hours→ 4 = 4;6 int totalMinutes→ 240 = hours4 * minutesPerHour60;78 std::cout << "hours=" << hours4 << std::endl;9 std::cout << "minutes=" << totalMinutes240 << std::endl;10 return 0;11}outputhours=4 minutes=240
Follow the Constant
hoursstarts at2.minutesPerHouris the constant60.minutes = hours * minutesPerHour.- The default calculation is
2 * 60. - The program prints
hours=2andminutes=120. | hours | minutesPerHour | minutes | | --- | --- | --- | | 1 | 60 | 60 | | 2 | 60 | 120 | | 4 | 60 | 240 |
Exercise: constants.cpp
Reproduce minutes=120, then use hours 1 and 4 to predict each minutes value.