Control(Selection) statements in c++

Introduction


In simple examples in the C++ programming language, commands were executed in one flow, i.e., one after the other, until the very end of the program. Sometimes in the program, some commands are executed under a certain condition.

For example, consider the following problem: For the entered numbers a and b, calculate the value of the fraction a / b.

After the declaration of variables and entries a and b by the user, we come to the part where it is necessary to calculate the fraction. Is it possible to simply introduce the variable c and calculate c = a / b?

It is known that division by zero is not allowed. This means that before writing the formula mentioned above, it must first be checked whether the condition that b is different from zero is met. If so, then you can write a formula and print the result. Otherwise, something alternative can be done, e.g., to display a message that division by zero is not allowed, or to do nothing.

We conclude that there are two variants of program execution, or only one, which depends on the condition of whether b is different from zero or not. This means that branching occurs in the program and that branching is done on the basis of logical data or expressions.

Branching in a program with 2 branches


Figure 1: Branching in a program: A comparison of a program in one stream and with program branching
Figure 1: Branching in a program: A comparison of a program in one stream and with program branching
Branching allows programs to make decisions based on given conditions, which opens up the possibility of customizing the execution flow. The previous figure shows the basic branching in a program with two branches, where each branch contains at least one command (command 2 in the left stream, and command 3 in the right).
However, there are situations when it is necessary to enable the execution of a certain command only if a certain condition is met, while in the second flow there are no commands to execute. This is called conditional execution, and the flow chart for such situations is shown in the following figure (Figure 2).
In the left flowchart, if the value of the condition is 0 (FALSE), the program skips statement 2 and continues without executing it. In the right flowchart, we see similar branching with the addition of the ability to skip execution in one branch if a condition is not met.
In C++, this kind of branching often uses keywords like if and else, and due to the existence of the bool data type, the expressions used for the condition can be more expressive and intuitive. For example:
if(condition){
// The statement is executed if the condition is true
statement2();
}
// The flow continues here without an additional branch

​​Similarities and differences with branching in the C language

Simililarities:

1. Basic branching structures:
  • Both languages ​​use if, else if, else, and switch to control program flow.
  • The syntax for these structures is identical:
if (condition) {
// Code to execute
} else {
// Alternative code
}
1. Logical expressions:

Both languages ​​use the same logical operators:
  • && (logical "and"),
  • || (logical "or"),
  • ! (logical negation).
2. Interruption and continuation of the flow in the switch structure:
  • Both languages ​​use break to break switch branching and default for default cases.

Differences


1. Data types in conditions


C:

In C, a condition in branching can be any expression that can be interpreted as an integer value:

  • 0 is considered false.
  • Anything other than 0 is considered true.

Example:

if (1) {
printf("This will always execute in C.\n");
}

C++:

C++ has stricter logic and supports the bool type introduced in C++98.

In C++, it is recommended to use bool for logical conditions, making the code more readable and less error-prone.


Example:

bool condition = true;
if (condition) {
std::cout << "This will execute in C++.\n";
}

2. Functionality in branching


C:

Does not support advanced mechanisms like lambda expressions or traditional std::function objects for logical expressions.


C++:

Provides additional features such as lambda expressions, enabling more complex and flexible branching:


auto condition = []() { returntrue; };
if (condition()) {
std::cout << "Lambda condition is true.\n";
}

3. Switch with complex expressions


C:

switch in C can only use integral types (int, char, enum).

C++:

In modern versions of C++ (C++11 and later), constexpr expressions and enum class can be used in switch structures, which is not possible in C.

4. Else if vs else if as a single block

C:

Technically, else if is not a specific keyword but rather a combination of else { if }.

C++:

The functionality remains the same, but due to stricter type logic, logical expressions in branching can be checked using compiler static analysis.

5. Integration with Object-Oriented Concepts (C++)

In C++, branching can integrate with class methods and properties, enabling more complex logic in object-oriented programs.


Conclusion

While basic branching structures in C and C++ remain similar, C++ provides additional functionality that allows for greater flexibility and better integration with modern programming practices, such as the use of bool type, lambda expressions, and constexpr evaluation. In C, the focus remains on simplicity and compatibility with older versions of the language.

​​Logical data

These are data whose value is the result of a logical expression and can have two states:
true
false
For the type of this data, the official word of the C ++ bool language is used
​

Logical data and expressions

​Logical relations ie. expressions are expressions that are actually the results of some comparisons, and use the following operators:
<, >, <=, >=, !, !=, ==

"Less than", "greater than", "less than or equal", "greater or equal", "negation", "not equal", "equally"

In C ++, you have a  special type for logical data (bool). It is a type that has two values: TRUE and FALSE.

Example of logical expressions in C ++

int a=10, b=8,c;
bool b;
c=a+b;    //integer expression
c=a>b;     //false
b=a>b;      //b=true
b=!(a>b);   //b=false

​

Logical data and more complex expressions​

Logical Data

These are data whose value is the result of a logical expression and can have two states:

  • true - true
  • false - false

The official C++ keyword for this type of data is bool.

Logical Data and Expressions


Logical relations, i.e., expressions, are expressions that are results of comparisons and use the following operators:


<, >, <=, >=, !, !=, ==

“less than,” “greater than,” “less than or equal to,” “greater than or equal to,” “negation,” “not equal to,” “equal to”


Example of Logical Expressions in C++

int a = 10, b = 8, c;
bool d;
c = a + b; // integer expression
c = a > b; // invalid, mismatched data types
d = a > b; // valid, results in true
d = !(a > b); // false

Logical Data and Complex Expressions

To combine multiple smaller logical expressions, we use the operators:

  • && – Logical “and”
  • || – Logical “or”

Assume we have the following code:


int a, b, c;
a = 10, b = 4, c = 2;
bool d, e;
d = (a == 0) && (b > c); /* d = false && true;
d = false; */

e = (a == 0) || (b > c); /* e = false || true;
e = true; */


Complex Logical Expressions with “&&”

A complex logical expression obtained by combining two simple logical expressions with && will be true only if both simple expressions are true, i.e.:

true && true = true
true && false = false
false && true = false
false && false = false

Complex Logical Expressions with “||”


A complex logical expression obtained by combining two simple logical expressions with || will be true if at least one of the simple expressions is true, i.e.:

true || true = true
true || false = true
false || true = true
false || false = false

​​Programming and logical data

​Logical data is used as a switch when branching in a program. The following figure(figure 2) shows the branches in the program based on the set condition. In the picture on the left, we show the conditional execution of command 2. First, command 1 is executed in one flow, and then the correctness of the condition is checked. If it is true, command 2 will be executed, and if it is not, none will be executed.
A condition on the diagram can be either a logical data of type bool or a logical expression, also of type bool.
In the picture on the right, branching into two branches is shown, based on the logical variable Condition (or logical expression). If it is correct, the branch to the left will be executed, i.e. command 2, and if false then command 3 will be executed.
This is made possible by an if statement (for the case on the left) or an if-else statement for the case on the right.Branching in the program, algorithm for the if-else statement
Figure 2: Branching in the program, algorithm for the if-else statement

​Branching in a program: the if-else statement

The if-else command enables branching in the program as shown in the following figure (Figure 3):
​Branching in a program: if-else statement, algorithm and syntax
Figure 3: Branching in a program: if-else statement, algorithm and syntax
​The picture shows the syntax of the command on the left, and the flow chart on the right. Here you can see that in the left branch, which is executed if the condition = true, command 2 (colored blue) is executed, and in the right branch, if the condition = false, command 3 (colored green) is executed. Branches can contain more than one statement, and then they must be enclosed in curly braces, as shown below:
// Commands 1
if(condition)
{
// Commands 2
}
else
{
// Commands 3
}
​If we don't have a statement in the second branch, then this branch serves to skip statement 2, and then only the if statement is used, without the else clause, as shown below.​

​Selections - command if

​Suppose command 1 is executed in 1 flow and then command 2 is executed if a certain condition is met, then the flow chart and code would look like in Figure 4. Conditional execution of a command is done using the if command:Branching in a program: if statement, no else, algorithm and syntax
Figure 4: Branching in a program: if statement, no else, algorithm and syntax
​A command branch can contain multiple commands as shown in the following example:
// Statements 1
if(condition)
{
// Statements 2
}
​Regardless of whether statements2 are to be executed or skipped, the program continues execution after the closing parenthesis.

​Example 1: ​Checking the correctness of the entered data

Task

Enter the length of the square's side a and check if the data is valid.

Note: The data is considered valid if it is a positive number.

Branching in the program: Example of the application of the if-else statement on the example that checks the correctness of the entered data
Figure 5: Branching in the program: Example of the application of the if-else statement on the example that checks the correctness of the entered data

Solution in C++

#include<iostream>
// Validate the input length of the square's side
using namespacestd;

int main() {
double a;
cout << "Enter the length of the square's side: ";
cin >> a;

if (a > 0) {
cout << "The entered length is valid: " << a << ".";
} else {
cout << "The entered length is not valid. The length must be a positive number.";
}

return 0;
}

Explanation

  • #include <iostream> includes the library for input and output operations.
  • cin is used to input the value of the variable a, representing the square's side length.
  • The program checks whether a is greater than zero:
    • If true, it prints a message stating that the length is valid.
    • If false, it warns that the length must be a positive number.
  • Finally, the program returns 0, indicating successful execution.

Test your code in the editor!

// Write your C++ code here...

​Example 2: Enter an integer and determine if it is divisible by 3

Solution:
​A number is divisible by 3 if the remainder of dividing the entered number by 3 is zero. We will use the if-else statement to create branching in the program, so that in one branch the message (cout) "The number is divisible by 3" will be printed, while in the other branch another message will be printed: "The number is not divisible by 3".
In order to write the condition for branching, it is necessary to determine the remainder of the division. The "%" operator is used for this.
Therefore, the remainder of the division of the number a and the number 3 is: a%3.
It is then checked to see if it is equal to zero. So,
a%3 == 0
#include <iostream>

/* Enter an integer and determine if it is divisible by 3 */
int main()
{
int a;
std::cout << "Enter an integer: " << std::endl;
std::cin >> a;
if ((a % 3) == 0)
std::cout << "Number " << a << " is divisible by 3" << std::endl;
else
std::cout << "Number " << a << " is not divisible by 3" << std::endl;
return 0;
}

Example 3: Enter two real numbers x and y, and calculate the value of the fraction

The first thing that might have happened to us is to solve the problem in the following way:
double a, b, fraction;
// Declare three variables: 'a', 'b' (real numbers) and 'fraction' (to store the result of division)

std::cout << "Enter two real numbers a and b!" << std::endl;
// Prompt the user to enter two real numbers

std::cin >> a >> b;
// Read the values of 'a' and 'b' from the user

fraction = a / b;
// Calculate the fraction by dividing 'a' by 'b'

std::cout << fraction;
// Output the result of the division
​However, the problem is that the formula for calculating the fraction must be valid for every real number. In our case, the problem is if the number 0 is found in the fractional name.
To ensure that there is no division if b is equal to zero, we will use the if command
double a,b, fraction;
cout << "Enter two real numbers a and b!" << endl; cin >> a >> b;
if(b != 0)
{
 fraction=a/b;
}

cout << fraction;
Here is an if command without clause else. If we would like to inform the user of the error in case of entering the value of zero for the reason rationale:
double a, b, fraction;
// Declare three variables: 'a', 'b' (real numbers) and 'fraction' (to store the result of division)

std::cout << "Enter two real numbers a and b!" << std::endl;
// Prompt the user to enter two real numbers

std::cin >> a >> b;
// Read the values of 'a' and 'b' from the user

if(b != 0)
{
fraction = a / b;
// Calculate the fraction by dividing 'a' by 'b' if 'b' is not zero
}
else
{
std::cout << "Error: You can't divide a number by zero" << std::endl;
// Display an error message if 'b' is zero
}

std::cout << fraction;
// Output the result of the division (or a default value if no division occurred)

A more detailed explanation of the "if" statement



The "if" statement allows conditional execution of code based on a specific condition.

Syntax:


if (condition) {
// Code to execute if the condition is true
}

Example with a simple condition:

#include <iostream>
using namespace std;

int main() {
int number;
cout << "Enter a number: ";
cin >> number;

if (number > 0) {
cout << "The number is positive." << endl;
  }

return 0;
}

In this example, the code inside the if block is executed only if the condition number > 0 is true.


Complex Conditions

Often, multiple conditions need to be evaluated. Logical operators such as && (AND) and || (OR) are used for combining conditions:


Example with logical operators:


#include <iostream>
using namespace std;

int main() {
int x, y;
cout << "Enter two values (x and y): ";
cin >> x >> y;

if (x > 0 && y < 10) {
cout << "x is positive and y is less than 10." << endl;
  }

if (x < 0 || y > 20) {
cout << "x is negative or y is greater than 20." << endl;
  }

return 0;
}

Explanation:

  • x > 0 && y < 10: Both conditions must be true for the code inside the if block to execute.
  • x < 0 || y > 20: The code executes if at least one condition is true.

Nested "if" Statements

When conditions are dependent, nested if statements can be used:


Example with nested "if":

#include <iostream>
using namespace std;

int main() {
int grade;
cout << "Enter a grade (1-5): ";
cin >> grade;

if (grade >= 1 && grade <= 5) {
if (grade == 5) {
cout << "Excellent!" << endl;
    } else if (grade == 4) {
cout << "Very good." << endl;
    } else if (grade == 3) {
cout << "Good." << endl;
    } else if (grade == 2) {
cout << "Sufficient." << endl;
    } else {
cout << "Insufficient." << endl;
    }
  } else {
cout << "Invalid grade!" << endl;
  }

return 0;
}

Explanation:

  • The outer if ensures the grade is valid.
  • The inner if-else block handles specific cases for grades.

Branching in a 3-branch program

​Branching in the program when we have 3 branches or more is achieved using the if-else if-else or if-else if-else if command. In the first case, 2 conditions are required, and in the second case, 3 conditions.​Now let's look at the first case with 2 conditions:Branching in a program with 3 branches in the C++ language, realized with two conditions (logical expressions).
Figure 7: Branching in a program with 3 branches in the C++ language, realized with two conditions (logical expressions).
The branching order according to the algorithm shown in Figure 4 would be:
// Statements 0
if(Condition1)
{
// Statements 1
}
else if(Condition2)
{
// Statements 2
}
else
{
// Statements 3
}

Explanation:

  1. Structure of the code:

    The code shows the structure of the if-else if-else statement in C++ language, which allows branching the program flow based on different conditions.

  2. Code elements:

    Condition1, Condition2 are logical expressions (conditions).

    • If Condition1 is true, statements 1 will be executed, and the other branches will be skipped.
    • If Condition1 is false, but Condition2 is true, statements 2 will be executed, and the other branches will be skipped.
    • If both Condition1 and Condition2 are false, statements 3 from the else block will be executed.
  3. Behavior description:
    • if (Condition1): Checks the first condition (Condition1). If it is true, it executes the code inside the first branch (statements 1), and the other branches are ignored.
    • else if (Condition2): Checks the second condition (Condition2) only if the first condition is false. If the second condition is true, it executes the code inside the second branch (statements 2).
    • else: Executes only if all the previous conditions are false. This block provides the "default" scenario (statements 3).
  4. Role of colors:

    Statements 1, 2, and 3 use different colors to highlight their function:

    • Green: Statements that execute for the first branch (if).
    • Red: Statements that execute for the second branch (else if).
    • Blue: Statements that execute in the final branch (else).
  5. Example use:

    Imagine a program that analyzes a student's grade and gives feedback:

​Instead of the last else block, we can put an else if block that requires the 3rd condition. This is shown in the pictureBranching in a program with 3 branches in the C++ language, realized with 3 conditions - algorithm
Figure 7: Branching in a program with 3 branches in the C++ language, realized with 3 conditions - algorithm
The figure shows another case, which is branching with 3 branches: The program first executes commands 0 in one flow (branch) and then divides based on the set 3 conditions into 3 branches. First, condition 1 is tested. If it is true, commands 1 will be executed. If that condition is not true, then condition 2 is tested. If it is true, commands 2 is executed. If condition 2 is not true, then condition 3 is tested. If it is true, it will execute is command 3, and if it is not, all commands will be skipped. After that, the program returns to a single flow (see how the arrows flow into the circle on the diagram).
The code represented by this diagram would be:
// Commands 0
if (condition1) {
// Commands 1
} else if (condition2) {
// Commands 2
} else if (condition3) {
// Commands 3
}

Branching in a program with more than 2 branches-video(with an English title)


Example 4: Enter the whole number and determine its sign, ie whether the number is positive, zero or negative

​We reserve the first memory for an integer a, and then enter it.
int a;
cin>>a;
Further, in order to determine whether the number is positive zero or negative, we use the selection statements, i.e. if - else if-else command:
if(a > 0) {
        cout << "The number is positive";
    }
    else if(a == 0) {
        cout << "The number is zero";
    }
    else {
        cout << "The number is negative";
    }
  
First, the first condition a> 0 is examined. If it is a point, the command will be executed within the braid brackets below the if, and then the remaining commands will be skipped.
If the first condition is incorrect, the program goes to another condition a == 0 next to else if.
If he is typing, the message "Number is equal to zero" and the rest of the expanded if the command is skipped.
If this condition is not true, then the command under another clause is executed. Note that besides else there are no conditions. It is not needed, because the command below is executed if all the previous conditions are incorrect. In this example, if the number was not positive and was not zero, it is assumed to be negative.
The clause else, if there is, is always the last. On the last, third place, instead of else, the command could end with else if. The difference over the other is that, besides else if it is necessary to write a certain requirement. In this example, the condition would be "a <0".
The next code would perform the set task in exactly the same way as it was performed using another clause in the last place:
if(a > 0){
  cout << "The number is positive";
} else if(a == 0){
  cout << "The number is zero";
}
else if(a <0 ){
  cout << "The number is negative";
}

Example 5: Input two real numbers via standard input and compare their values

Solution:

After entering the numbers a and b from the keyboard, the program branches into 3 possible paths, since there are 3 possible outcomes. These outcomes are actually messages that will be printed using the cout command:

  • "a is greater than b"
  • "a is equal to b"
  • "a is less than b"

First, we need to set the first condition using the if statement, for example, whether a is greater than b (a > b). With this condition, we get two possible branches: one for the true condition, in which case the first message is printed, and another for the false condition. Since there are two other possibilities, we need at least one more condition. For example, "is a equal to zero?" (a == 0). This goes with the else if clause immediately below the first branch. The second outcome will be printed if this condition is true. The third outcome will be printed if this condition is false, and it is handled by the else clause.

The code below demonstrates this process:

#include <iostream>
using namespace std;

// Program that prints the relationship between two numbers a and b
int main() {
int a, b;
cout << "Enter number a: ";
cin >> a;
cout << "Enter number b: ";
cin >> b;

if (a > b) {
cout << "a is greater than b" << endl;
} else if (a == b) {
cout << "a is equal to b" << endl;
} else {
cout << "a is less than b" << endl;
}

return 0;
}
Explanation:

Of the three possible outcomes, i.e., three possible messages, only one will be executed:
  • For the first condition being true, the first message will be executed.
  • For the first condition being false, but the second condition true, the second message will be executed.
  • For both the first and second conditions being false, the third message will be executed.

It is also important to note that the else clause, which can only be the last one, does not require an explicit condition to be written; it is implied. This means: if a > b is false and a == b is false, we conclude that a < b.

This can also be solved using an else if statement at the last position, but it would require an explicit condition:
#include <iostream>
using namespace std;

// Program that displays the relationship between two numbers a and b
int main() {
int a, b;
cout << "Enter number a: ";
cin >> a;
cout << "Enter number b: ";
cin >> b;

if (a > b) {
cout << "a is greater than b" << endl;
} else if (a == b) {
cout << "a is equal to b" << endl;
} else if (a < b) {
cout << "a is less than b" << endl;
}

return 0;
}
Brackets were not used to write commands as program variants in branching, because there is only one command in each branch. In case there are multiple statements within one of the branches, enclosing those statements within a curly brace block would be mandatory.

Branching in a Program Based on the Value of an Integer Variable – switch Statement


Program branching can be performed not only based on one or more conditions but also based on different values of an integer variable, as shown in Figure 8.

Before branching occurs, an integer variable must be entered, assigned, or computed earlier in the code. Based on its possible values, branching is performed. Each of these possible values leads to a different branch in which certain commands will be executed (see Figure 8). If the variable's value is different from the offered ones, the program will take the default branch and execute its commands, if defined.

Branching in a program based on the value of an integer variable
Figure 8: Branching in a program based on the value of an integer variable

The switch statement is used to branch the execution of a program based on the value of an integer variable. In the example below, a variable named data is defined and loaded, then the switch statement evaluates its value. Three cases (e.g. value_1, value_2, value_3) are provided, along with a default branch that is executed if none of the specified values match.

#include<iostream>using namespacestd;intmain() {
    intdata; // Declare the variable datacout << "Enter data: " << endl; // Prompt for inputcin >> data; 

switch(data) { case1: // If data equals value_1cout << "Value 1 selected" << endl;// commands 1break; case2: // If data equals value_2cout << "Value 2 selected" << endl;// commands 2break; case3: // If data equals value_3cout << "Value 3 selected" << endl;// commands 3break; default: // If data does not match any casecout << "Default case: value not recognized" << endl; break; } return0; }

Example 6: Determining the Month Based on the Month Number


In this example, we demonstrate how to use the switch statement to determine the month name from an input month number. A variable named month is defined and loaded with the user input. The switch statement then checks the value of month and directs the flow to one of three specific cases – for example, case 1, 2, and 3 – each printing a corresponding month name (January, February, March). If the input does not match any of the defined cases (i.e. if the number is less than 1 or greater than 12), the default branch is executed and an error message is displayed.

#include<iostream>using namespacestd;intmain() {
    intmonth; // Declare the month variablecout << "Enter the month number: " << endl; // Prompt for inputcin >> month; 

switch(month) { case1: // If month equals 1cout << "January" << endl; break; case2: // If month equals 2cout << "February" << endl; break; case3: // If month equals 3cout << "March" << endl; break; default: // For any other value (invalid month)cout << "Invalid input: month must be between 1 and 12" << endl; break; } return0; // End of program }
The algorithm of this code is shown in Figure 9.
Example of using the switch command, algorithm: Entering the name of the month based on the entered ordinal number of the month.
Figure 9: Example of using the switch command, algorithm: Entering the name of the month based on the entered ordinal number of the month.

Example 7: Determining the Number of Days in a Month

This program calculates the number of days in a month based on the user's input. The program reads an integer for the month and an integer for the year, then uses a switch statement to assign the correct number of days for that month. For February, it checks if the year is a leap year using the condition:


year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)
  

If the month is not valid (i.e. not between 1 and 12), the default branch is executed and an error message is displayed. Otherwise, the program prints the number of days for the specified month.

#include<iostream>using namespacestd;intmain() {
    intmonth, year;
    intnumOfDays;
    cout << "Enter the month and year!" << endl; // Prompt for inputcin >> month >> year;
    boolinvalidInput = false;

    switch(month) {
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:
            numOfDays = 31;break;case 4:
        case 6:
        case 9:
        case 11:
            numOfDays = 30;break;case 2:
            if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)) {
                numOfDays = 29;// Leap year
            } else {
                numOfDays = 28;
            }
            break;default:
            invalidInput = true;
    }

    if (!invalidInput) {
        cout << "Number of days is: " << numOfDays << endl;
    } else {
        cout << "Invalid Input" << endl;
    }

    return0;
}
  

Example 8: Selecting figures

Task:
​Enable first the user to choose one of three geometric shapes:
 1-Square, 2-Circle, 3-Parallelogram,
and then enter the required input data for the selected figure and calculate its area
You can find examples of branching in the program on the webpage Selection statements - examples

Advanced Examples



Advanced examples can greatly enrich the content for experienced programmers by demonstrating complex decision-making in code. By incorporating examples with multiple conditions, nested if-else structures, and combined logical expressions, you can solve real-world problems with intricate logic.

For instance, consider a scenario where you need to determine a student's grade based on several criteria such as test scores, attendance, and assignment performance. A nested if-else structure with combined logical conditions can elegantly handle multiple criteria and edge cases.

Below is an example code snippet that demonstrates advanced branching using nested if-else statements and combined logical expressions:

#include<iostream>using namespacestd;intmain() {
    intscore;
    cout << "Enter your score: " << endl; // Prompt for the student's scorecin >> score;
    
if (score >= 90) { if (score >= 95) { cout << "Grade: A+" << endl; // Score 95 or above gives A+ } else { cout << "Grade: A" << endl; // Score between 90 and 94 gives A } } else if (score >= 80 && score < 90) { cout << "Grade: B" << endl; } else if (score >= 70 && score < 80) { cout << "Grade: C" << endl; } else { cout << "Grade: F" << endl; }
return0; // End of program }

In this example, nested if-else statements and combined logical conditions are used to determine the grade based on the student's score. The inner if-else distinguishes between an A+ and an A grade when the score is 90 or above, while other conditions determine grades B, C, or F. This demonstrates how advanced branching structures can handle multiple criteria in a single decision-making process.

Modern C++: if (init; cond) and if constexpr

In modern C++ (C++17+), we can initialize a variable directly in the if condition. Also, if constexpr allows compile-time branching.

if (int x = 5; x > 0) {
// works with local x
  std::cout << "Positive";
}

if constexpr (sizeof(int) > 2) {
  std::cout << "int is 32-bit or larger";
}

Switch and [[fallthrough]] in C++17

When using switch, we can explicitly allow execution to continue into the next case by using the [[fallthrough]] attribute.

switch(n) {
case 1:
    std::cout << "One";
[[fallthrough]];

case 2:
    std::cout << "Two";
break;
}

Previous
​|<Operators in C++
​Next
​Loops in C/C++>|

Related articles

Selection statements-examples
Data in C/C++
Selection statements in JAVA
Arrays-examples
Algoritms