Skip to content

Conditional statements in C++ (1)

Course: C++ Part 1 - chapter 5

C++ like Javascript has the following conditional statements:

  1. if else
  2. switch
  3. conditional operator
if (condition_1) {
// Executed if condition_1 is true
} else if (condition_2) {
// Executed if condition_1 is false and condition_2 is true
} else {
// Executed if both condition_1 and condition_2 are false
}

We can even have nested if else statements or just single if statement

// Only if statement
if (condition) {}
// Nested if else
if (condition_outer) {
if (condition_inner) {}
else {}
} else {}
switch(variable) {
case 1:
// When variable is 1
break;
case 2:
// When variable is 2
break;
default:
// When none of the case statements is satisfied
}

💡 The case value must be of type integer or character

💡 Like Javascript, default statement is optional. Also break keywords are optional.

condition ? true_statement : false_statement

Examples:

bool is_even = (n % 2 == 0) ? true : false;
int absolute_diff = (a > b) ? a - b : b - a;