Decision-making statements are crucial in C and C++ programming, and many developers write inefficient code without knowing it. By using these statements, you can control program flow with if-else, switch, and the ternary operator. But are you using the best one? Improper use of nested if statements, redundant conditions, or handling false in switch cases may slow down your code. Are you making these common mistakes that affect C++ control flow? This article breaks down the decision-making statements in C/C++, with syntax, examples, and best practices to help you write cleaner and efficient code.
Table of Contents:
What are Decision-Making Statements in C/C++?
Decision-making is an integral part of the code. Based on the specific conditions, it allows the execution of different blocks of code. We use decision-making statements in the program to control the flow based on logical conditions. C++ decision-making statements, also known as conditional statements, are based on the conditions that control the flow of the program. Mostly, the conditions are typically in Boolean expressions, and the code gets executed only if the condition is true; Otherwise, it does not. This is how you manage C and C++ control flow.
For example, if we want to check if a Number is Positive, Negative, or zero. For this type of scenario, we need to use the C and C++ decision-making statements to effectively manage C and C++ control flow.
Common Uses of Decision-Making Statements in C/C++
Here are the real-life scenarios where the C++ decision-making statements are used:
- Loop Control: C++ decision-making statements are widely used within loops to control the execution and direct control flow.
- Error Handling: Conditional statements help in handling errors or unexpected conditions, influencing C++ control flow.
- Authentication: The C++ decision-making statements are widely used in authentication systems to compare the user’s input against the stored credentials, to determine whether to grant or deny access.
- Control Flow: By using C++ decision-making statements, we can easily control the flow of execution in a program.
Different Types of Decision-Making Statements in C and C++
There are several types of C and C++ decision-making statements. Let’s discuss them in a detailed way:
- if Statement
- if-else Statement
- if-else-if Statement
- Nested if Statement
- Switch Statement
- Conditional (Ternary) Operator
- Jump Statements
1. if Statement in C/C++
In C and C++, the if statement is a fundamental decision-making statement that allows the program to execute a block of code only if the specified condition is true. And it skips the code if the condition is false, which directly influences C and C++ control flow. Also, when thinking about if vs switch performance in C++, if statements are generally straightforward and evaluated sequentially.
Syntax:
if (condition) {
// Code to execute if the condition is true
}
If statement works as follows:
- If the condition is true, then the statement inside the {} block is executed.
- If the condition is false, then the statement inside the {} block is avoided.
C Decision-Making Example Using if Statement:
Output:
In C, the if statement checks if a condition is true or not; if it is true, it executes the block of code; otherwise, it skips the code. It takes the input using scanf(), and using an if statement, it checks whether the number is greater than zero. If it is true, it prints “The number is positive: using printf(). If the condition is false, the statement skips the blocks and continues the next execution.
Example of an if statement in C++:
Output:
In C++, the if statement works the same way as in C, using cin and cout. It takes the inputs and outputs. It first checks the condition. If it is true, it executes the block and prints the output. If the statement is false, it skips the block and executes the next statement.
2. if-else Statement in C/C++
When you need to execute one block of code, the if-else statement is used:
- If the condition is true, then the program executes the first block.
- If the condition is false, the first block gets skipped, and the else block is executed.
Syntax:
if (condition) {
// Code executes if a condition is true
} else {
// Code executes if a condition is false
}
- If the statement is true, it executes the if block.
- If the statement is false, it executes the else block.
C Decision-Making Example Using if-else:
Output:
In C, the if-else statement checks whether the number is positive or negative. If the value is positive, it executes the if statement. If the value is negative, it executes the else statement.
Example of an if-else statement in C++:
Output:
In C++, the if-else statement checks whether the number is positive or negative; if the value is positive, it executes the if statement. Otherwise, it executes the else statement. Later, it prints the statements, using cout.
3. if-else-if Statement in C/C++
You can check multiple conditions sequentially by using an if-else-if statement. The first if condition is the beginning of the evaluation. If the condition is found to be True, the statement is executed, and the rest of the statements are skipped. If the condition is false, it moves to the next else-if condition and keeps checking until it gets a true condition. The last else block is used as the default if none of the conditions are true. This method works efficiently with anything that has binary possibilities, like grading systems, voting systems, etc.
Syntax:
if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition2 is true
} else if (condition3) {
// Code to execute if condition3 is true
} else {
// Code to execute if none of the conditions are true
}
- If condition1 is true, it executes the block and skips the rest.
- If the condition is false, it immediately checks the condition2
- If no conditions are true, by default, it executes the else block.
C Decision-Making Example Using if-else-if Statement:
Output:
In C, the above program uses scanf() for input and checks the range using an if-else-if statement. If the marks are above 90, it prints “Grade A’, if between 80-89 it prints “Grade B”. And if the marks are below 60, it prints “Grade F”. The else block works as a default if the marks are less than 60.
Example of an if-else-if statement in C++:
Output:
The above programs work the same as C but use cin and cout for input and output. It follows the same method as checking the conditions sequentially and printing the grade.
4. Nested if Statement in C/C++
An if statement inside another if statement is called a nested if statement, and it is used for checking multiple related conditions. First, the outer if condition is checked, and in case of false, the inner if will be skipped. If the outer condition is true, check the inner if condition, and if it is true, execute the inner if block. This is useful in structures like user authentication (where you first check the username, and then you check the password) or eligibility checks (where you first check whether the person is of age, and then check all others).
Syntax:
if (condition1) {
// Code executes if condition1 is true
if (condition2) {
// Code executes if both condition1 and condition2 are true
}
}
- It first checks the condition1.
- If condition1 is true, it checks condition2.
- If condition1 is false, it automatically skips the inner if.
C Decision-Making Example Using nested-if statement:
Output:
First, the program requests user input for both age and citizenship. In the outer ‘if’, we check whether the user is 18 or older. Otherwise, it prints, “You must be at least 18 years old to vote,” and exits. Inside the first if, if the age condition matches, it checks whether the user is a citizen (Y or y). If so, it prints “You are eligible to vote, else it prints “You must be a citizen to vote”.
Example of a nested-if statement in C++:
Output:
The C++ program uses cin and cout for input and output. Inside the first if, if the age condition matches, it checks whether the user is a citizen (Y or y). If so, it prints “You are eligible to vote, else it prints “You must be a citizen to vote.”
5. Switch Statement in C/C++
The switch statement checks a value and executes the matching case by avoiding multiple if-else statements. Here, each case runs a particular code, and a break has been used so that the program execution is not transmitted to the next statement. If none of the conditions match, then the default block will be executed. When evaluating if vs switch performance in C++, always consider the number of conditions, as switch statements handle multiple constant cases more efficiently, while if-else chains may become slower and harder to read with many conditions.
Syntax:
switch (expression) {
case value1:
// Code to execute if expression == value1
break;
case value2:
// Code to execute if expression == value2
break;
case value3:
// Code to execute if expression == value3
break;
default;
// Code to execute if no cases match
}
- The expression is evaluated only if the matching case executes.
- The break statement prevents the execution from falling into the next case.
- If no matches are found, then the default case is executed.
C Decision-Making Example Using switch statement:
Output:
Depending on the operator (+, -, *, /), the switch statement operates. In the default case, an error is output if an invalid operator is given. For division, the program checks that the divisor is zero before attempting the operation to avoid errors. The break statement ensures that only the matching case executes.
Example of a switch statement in C++:
Output:
The C++ program executed the program same way as the previous one, but uses cin and cout for input and output. Based on the user input, the switch statement selects the correct arithmetic operation. If an invalid operator is entered, the default case manages it.
6. Conditional (Ternary) Operator in C/C++
The ternary operator in C++ and C is similar to the if-else statement. Is it written as a condition? value_if_true : value_if_false. Depending on the single line, these conditional operators are used for executing the different lines of code; they return two values based on condition is true or false.
Syntax:
variable = (condition)? value_if_true : value_if_false;
- The condition evaluates the expression.
- Value_if_true assigns the values if the condition is true
- Value_if_false assigns the values if the condition is false.
C Decision-Making Example Using Ternary Operator:
Output:
The above program takes the two numbers, using the ternary operator, and checks if num1 is greater than num2. If it is greater than num1 is assigned to max; otherwise, num2 is assigned. By using the printf(), the largest number is printed.
Example of a Ternary Operator in C++:
Output:
The above works the same as the previous; The program takes the two numbers, using the ternary operator, and checks if num1 is greater than num2. If it is greater than num1, it is assigned to max; Otherwise, num2 is assigned. By using the cout, the largest number is printed.
7. Jump Statements in C/C++
Jump statements in C++ and C are used to change the flow of execution in the code by transferring control from one part of the code to another. We can skip iterations, exit the loops, or jump to certain points using these statements. The jump statements, supported by C and C++, are:
- break: Exits from the nearest loop/switch statement immediately.
- continue: Skips the current iteration of a loop and goes to the next iteration.
- goto: Transfers control to a labeled statement elsewhere in the program.
- return: Exit a function and optionally return a value (in functions).
What is Semantic Equivalence?
Semantic equivalence means that the same output or the same operation is performed by two programs. This approach is highly effective when it comes to code refactoring, code optimizations, and teaching programming concepts.
The most common control statements that can be interchanged are:
- if-else and switch
- for and while, and do-while
- loop and recursion
Using if-else
The code below represents the usage of if-else:
Example:
Output:
This is a program that checks the day and prints the weekday with if-else-if, where day = 2 means Tuesday.
Using switch
The code below represents the usage of the switch:
Example:
Output:
This is a program that uses a switch to check the day and prints the weekday, where day = 2 means Tuesday.
Common Mistakes and Pitfalls of Decision-Making Statements
- Using = instead of == in conditions causes unintended value assignments.
- Forgetting to use braces {} can lead to logic errors when adding multiple lines.
- Not handling all possible conditions can cause incomplete program behavior.
- Relying too much on nested if statements can make code hard to read.
- Using else if when separate if statements are needed can skip conditions.
- Missing the default case in a switch statement can leave unexpected inputs unhandled.
- Forgetting a break in a switch case leads to unintended fall-through.
- Writing overly complex conditions makes the code harder to understand and debug.
- Misusing data types in conditions (e.g., using integers instead of booleans) can confuse users.
- Not testing all decision paths may leave bugs undetected in certain inputs.
Best Practices to be followed while using Decision-Making Statements
- Always use == for comparisons, not =.
- Use curly braces {} even for single-line if or else blocks.
- Keep conditions clear and easy to understand.
- Use else if or else to handle alternative cases properly.
- Prefer to switch over to if-else when checking fixed constant values.
- Always include a default case in switch statements.
- Don’t forget break statements in each switch case.
- Avoid deeply nested if statements by simplifying logic where possible.
- Add comments to explain complex decision branches.
- Test all condition paths, especially edge cases.
Conclusion
In C and C++, based on the conditions, decision-making statements are very important for controlling the flow of a program. These statements include if, if-else, switch, and ternary operators, which help to execute a specific block of code in a program. Also, the jump statements in C++ are essential while altering the execution flow. By mastering the concept of C and C++ decision-making statements, programmers can easily implement logical statements like loops and error-handling. These decision-making statements enhance readability and efficiency.
You can learn more about C++ in the C++ article, and also explore C++ Interview Questions prepared by industry experts.
Decision-Making Statements in C/C++ – FAQs
Q1. What are C and C++ decision-making statements?
In C/C++, decision-making statements are used in the program to control the flow based on logical conditions, such as if, if-else, switch, and ternary operators.
Q2. How to use if else statements in C++?
Use if to check a condition, and else to run alternate code when the condition is false.
Q3. What is the purpose of the switch statement?
The switch statement checks a value and executes the matching case by avoiding multiple if-else statements.
Q4. How the ternary operator in C++ works?
The ternary operator in C++ evaluates a condition and returns one of two values: condition ? value_if_true : value_if_false.
Q5. What are jump statements in C++?
Jump statements in C++ are used to change the flow of execution in the code by transferring control from one part of the code to another. The jump statements consist of break, continue, goto, and return.
Q6. When should you prefer switch over nested if in C/C++?
Prefer to switch over nested if when checking a single variable against multiple constant values for better readability and performance.
Q7. Can ternary operators affect readability?
Yes, ternary operators can affect readability if overused or nested, making code harder to understand.
Q8. Is goto still used in modern C++?
Goto is rarely used in modern C++ as it can lead to confusing and hard-to-maintain code, and is generally discouraged.
Q9. How to avoid fall-through bugs in switch?
To avoid fall-through bugs in switch, always use break after each case unless intentional fall-through is needed and clearly commented.
Q10. How do if vs switch differ in assembly or runtime performance?
At runtime, a switch can be faster than if-else chains, as it may be optimized into jump tables or binary searches by the compiler.