C++ provides you with tools which helps you to control the way your program behaves (logic flows) based on how the user interact with your program. Here we will discuss about if-else, switch and goto are three common ways to guide the flow of logic in your code.
Use if-else when you want your program to choose between two possible actions.
#include <iostream>
int main() {
int age = 18;
if (age >= 18) {
std::cout << "You can vote!" << std::endl;
} else {
std::cout << "Too young to vote." << std::endl;
}
return 0;
}
Explanation: The program checks the condition inside if. If it’s true, the first block runs. If it’s false, the else block runs.
Use switch when you have multiple possible outcomes for one variable. It’s often cleaner than using many if-else statements.
#include <iostream>
int main() {
int day = 3;
switch (day) {
case 1: std::cout << "Monday"; break;
case 2: std::cout << "Tuesday"; break;
case 3: std::cout << "Wednesday"; break;
default: std::cout << "Invalid day";
}
return 0;
}
Explanation:
The goto statement allows you to jump directly to another part of your code. Although it works, it is not recommended because it makes programs harder to understand and maintain.
#include <iostream>
int main() {
int x = 5;
if (x == 5)
goto label;
std::cout << "This line will be skipped." << std::endl;
label:
std::cout << "Jumped to label!" << std::endl;
return 0;
}
Explaination:
Visit the following resources to learn more: