Introduction

Welcome! Today, we are unraveling the crucial aspects of C++ control structures, specifically the if, else, and switch statements. Control structures steer the flow of your program based on conditions, which is similar to decision-making in daily life. Fascinating, isn't it? Let's dive right in.

The anatomy of the `if` statement

The if statement checks a given condition inside parentheses, which must result in a boolean value (true or false):

if (condition) {
    // Code to be executed if the condition is true
}
  • The condition is placed between the parentheses ().
  • If the condition evaluates to true, the code block within the curly braces {} executes.
  • This block will not run if the condition is false.
`if` Statement in action

Consider a scenario at a restaurant. When you are hungry, you order food. This situation can be modeled in C++ using the if statement, as illustrated below:

#include <iostream> 

int main() {
   bool isHungry = true;

   if (isHungry) {
       //The following line will only be executed if isHungry is true
       std::cout << "Order food!";
   }

   return 0;
}

The if statement checks the condition: isHungry. If it's true, the statement within the block is executed. In this case, it prints "Order food!".

Digging Deeper into `if-else` Structures

The if-else statement in C++ tests a condition, then executes a certain task if the condition is met and performs a different task if not fulfilled. For instance, in a restaurant, you have a choice between the special dish or a juice, based on whether you're hungry or not:

#include <iostream> 

int main() {
   bool isHungry = false;

   if (isHungry) {
       //Executed when isHungry is true
       std::cout << "Order the special dish!";
   } else {
       //Executed when isHungry is false
       std::cout << "Just order a juice.";
   }
 
   return 0;
}
Exploring Comparison Operators within Control Structures

Before diving deeper into control structures, it’s essential to understand the role of comparison operators. These operators allow us to compare two values, resulting in a boolean value (true or false). This outcome determines the flow of control structures like if, else if, and switch.

Here are the most commonly used comparison operators in C++:

  • == checks if two values are equal.
  • != checks if two values are not equal.
  • > checks if the left value is greater than the right.
  • < checks if the left value is less than the right.
  • >= checks if the left value is greater than or equal to the right.
  • <= checks if the left value is less than or equal to the right.
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal