Error Detection and Handling
Short drills to make the concepts stick — predict what code prints, fix a broken snippet, or write a small function. Commit to an answer before you run anything.
9.3 — Common semantic errors in C++
What does integer division produce here?
The variable rate is declared as double. What does the program print?
#include <iostream>
int main()
{
int passed = 7;
int total = 10;
double rate = passed / total;
std::cout << rate << '\n';
return 0;
}Assignment inside an if condition
What does this program print? Look carefully at the operator inside the if.
#include <iostream>
int main()
{
int x { 0 };
if (x = 5)
std::cout << "branch taken, x = " << x << '\n';
else
std::cout << "branch skipped, x = " << x << '\n';
return 0;
}9.5 — std::cin and handling invalid input
Fix the cin recovery order
The function reads one int from std::cin and should return the value on success or -1 on failure. The snapshot and clear() are in the wrong order — fix it.
Edit student.cpp, then Run to check it against the tests.
9.6 — Assert and static_assert
Fix clampToRange: in-range values return wrong result
The function compiles and handles out-of-range inputs correctly, but returns the wrong value when the input is already inside [lo, hi]. Fix it.
Edit student.cpp, then Run to check it against the tests.
9.4 — Detecting and handling errors
Write isValidQuantity
Implement the function so all tests pass. Valid quantities are integers in the inclusive range [1, 999].
Edit student.cpp, then Run to check it against the tests.