C++ Beginner · Lesson 06 of 22
Control flow: if, else and switch
Making decisions, comparing values, and the C++17 if-with-initializer.
Estimated time · 45–75 min
Learning goals
What you will understand
- Explain control flow: if, else and switch in your own words
- Use it in a small robotics example
- Verify the result instead of assuming it worked
Understand the idea first
The mental model
if/else runs code only when a condition is true. switch chooses among several whole-number or enum values and should end each case with break. Prefer an enum class for states so a switch can list every case.
C++17 lets an if declare a variable that only exists inside the if and its else: if (auto x = f(); x > 0). This keeps temporary values from leaking into the rest of the function.
Guided lesson
Work through these steps
- 1.
Read the control flow: if, else and switch example and identify what each line owns or changes.
- 2.
Create a small source file, compile with -std=c++17 and warnings enabled, and run it.
- 3.
Change one input, predict the result before running, then compare the output.
- 4.
Record one compiler or runtime error and explain the correction in your own words.
Worked example
Read it before you run it
enum class Mode { idle, moving, fault };
// A scoped enumeration: only three legal states and no accidental int conversions.
Mode mode{Mode::moving};
// Start in the moving state.
switch (mode) {
// Choose a branch based on the current mode.
case Mode::idle: std::cout << "waiting\n"; break;
// Idle: print and leave the switch (break stops fall-through).
case Mode::moving: std::cout << "in motion\n"; break;
// Moving: print and leave the switch.
case Mode::fault: std::cout << "STOP\n"; break;
// Fault: print and leave the switch.
}
// End of the switch.
if (const double temp = read_temperature(); temp > 80.0) {
// C++17 initializer: temp exists only in this if/else and is tested at once.
std::cout << "too hot\n";
// Runs when the motor is above 80 degrees.
} else {
// Otherwise...
std::cout << "ok\n";
// ...the temperature is acceptable.
}
// End of the if/else.What the example is doing
- 1.Read declarations from right to left: identify each value's type, name, and initial value.
- 2.Follow the data through each expression before considering syntax shortcuts.
- 3.Compile with warnings enabled; a clean build is part of the result, not an optional polish step.
Watch it run · Values in memory
See what this code does
The terminal types this lesson's practice solution and runs it. The scene shows the kind of robot behaviour that code drives. It plays by itself and loops.
Demo for Control flow: if, else and switch. Expected result: close stop
Practice code
Now type it yourself
Copy the starter into practice.cpp and replace every TODO with your own code. Build and run it: g++ -std=c++17 -Wall -Wextra -Wpedantic practice.cpp -o practice -pthread && ./practice
#include <iostream>
enum class State { open, closing, closed, fault };
const char* next_action(State s) {
switch (s) {
// TODO: add a case for each state: open -> "close", closing -> "wait", closed -> "open", fault -> "stop"
}
return "none";
}
int main() {
std::cout << next_action(State::open) << '\n';
std::cout << next_action(State::fault) << '\n';
return 0;
}Expected output
close
stopStuck? Show the full solution (try it yourself first)
#include <iostream>
enum class State { open, closing, closed, fault };
const char* next_action(State s) {
switch (s) {
case State::open: return "close";
case State::closing: return "wait";
case State::closed: return "open";
case State::fault: return "stop";
}
return "none";
}
int main() {
std::cout << next_action(State::open) << '\n';
std::cout << next_action(State::fault) << '\n';
return 0;
}Expected result
How you know it worked
- After adding the shown fragment to the guided exercise with its listed headers and surrounding program, the finished program builds with -Wall -Wextra -Wpedantic.
- Changing the stated input produces the result you predicted.
Practical exercise
Apply the lesson
Model a gripper with an enum class State { open, closing, closed, fault } and a switch that prints the next allowed actions for each state. Add an if with initializer that reads a force value and enters fault above 40 N.
Before you continue
- The program builds with -std=c++17 and no warnings
- You can explain the key rule without reading the example
- The normal and edge cases both have recorded results
If something goes wrong
Start at the first error. Check spelling, required #include lines, and whether the declaration appears before use.
Print the inputs and intermediate values, then check conversions, units, and collection order.