Foundations
Conditionals
An if statement lets C++ choose between branches.
if statement
An `if` statement runs one block when its condition is true and can use `else` for the other case.
Conditionals
conditionals.cpp
Replay: real traced execution (multi-file project)
#include <iostream>
#include <string>
int main() {
int temperature = 72;
std::string status = "";
if (temperature >= 80) {
status = "warm";
} else {
status = "comfortable";
}
std::cout << "temperature=" << temperature << std::endl;
std::cout << "status=" << status << std::endl;
return 0;
}
#include <iostream>
#include <string>
int main() {
int temperature = 55;
std::string status = "";
if (temperature >= 80) {
status = "warm";
} else {
status = "comfortable";
}
std::cout << "temperature=" << temperature << std::endl;
std::cout << "status=" << status << std::endl;
return 0;
}
#include <iostream>
#include <string>
int main() {
int temperature = 90;
std::string status = "";
if (temperature >= 80) {
status = "warm";
} else {
status = "comfortable";
}
std::cout << "temperature=" << temperature << std::endl;
std::cout << "status=" << status << std::endl;
return 0;
}
temperature ← 72, status ← (empty)
4int main() {5 int temperature→ 72 = 72; //@temperature=55, 906 std::string status→ (empty) = "";status ← comfortable
9 status = "warm";10} else {11 status→ comfortable = "comfortable";12}std::cout << "temperature=" << temperature << std::endl;
14 std::cout << "temperature=" << temperature72 << std::endl;15 std::cout << "status=" << statuscomfortable << std::endl;16 return 0;17}outputtemperature=72 status=comfortable
temperature ← 55, status ← (empty)
4int main() {5 int temperature→ 55 = 55;6 std::string status→ (empty) = "";status ← comfortable
9 status = "warm";10} else {11 status→ comfortable = "comfortable";12}std::cout << "temperature=" << temperature << std::endl;
14 std::cout << "temperature=" << temperature55 << std::endl;15 std::cout << "status=" << statuscomfortable << std::endl;16 return 0;17}outputtemperature=55 status=comfortable
temperature ← 90, status ← (empty)
4int main() {5 int temperature→ 90 = 90;6 std::string status→ (empty) = "";status ← warm
8if (temperature90 >= 80) {9 status→ warm = "warm";10} else {std::cout << "temperature=" << temperature << std::endl;
14 std::cout << "temperature=" << temperature90 << std::endl;15 std::cout << "status=" << statuswarm << std::endl;16 return 0;17}outputtemperature=90 status=warm
Follow the Branch
temperaturestarts at72.statusstarts as an empty string.- C++ checks whether
temperature >= 80. 72is below80, so theelsebranch setsstatustocomfortable.- The program prints
temperature=72andstatus=comfortable. | temperature | check | status | | --- | --- | --- | | 55 |55 >= 80is false | comfortable | | 72 |72 >= 80is false | comfortable | | 90 |90 >= 80is true | warm |
Exercise: conditionals.cpp
Reproduce status=comfortable for temperature 72, then try 55 and 90 and predict the branch result.