1. Multi-branch if
Simple conditional structures were discussed earlier. Conditional structures are used to implement decision logic: a logical condition determines whether a block of code is executed, skipped, or whether two different actions are taken. The if and if-else structures are two common ways in the C language to implement a single logical condition check. In some cases you need to check multiple conditions. To handle those situations you can use multi-branch if, nested if, or switch. This section describes the multi-branch if structure.
The multi-branch if statement in C allows checking multiple conditions and executing corresponding actions based on the results. The syntax is:
if(< condition1 >) < statement_block >
else if(< condition2 >) < statement_block >
else if(< condition3 >) < statement_block >
......
else < statement_block >
This structure evaluates conditions from top to bottom. Once a condition is satisfied, the associated statements are executed and the remaining conditions are skipped. If none of the conditions match, the final else block is executed. If no final else is provided, no action is taken and execution continues after the conditional structure. When a statement block contains multiple statements, enclose them with '{' and '}'.
Example:
#include <stdio.h>
int main()
{
int x = 10;
if (x > 0) {
if (x > 5) {
printf("x is greater than 0 and 5\n");
}
}
return 0;
}
In this example an integer x is initialized to 10. Two nested if statements check x's value. The outer if checks whether x is greater than 0. If true, the inner if checks whether x is greater than 5. If that is also true, a message is printed indicating that x is greater than both 0 and 5.
Note that conditions after an if must be enclosed in parentheses, and the statements executed when the condition is true should be enclosed in braces. If the condition is false, the block is skipped and execution continues. Multiple nested if statements can be used to check several conditions, but excessive nesting reduces readability and maintainability.
2. Nested if
A nested if is a conditional structure used to perform multi-level decision checks in programming or logic. It makes decisions based on a series of conditional expressions and executes different actions depending on the situation.
A nested if statement consists of two or more if statements where each if may contain one or more conditional expressions. The inner statement executes only when the outer condition(s) are true.
For example, to determine whether a student's score is passing or excellent, you can use nested if statements. Pseudocode:
IF score >= 60 THEN
IF score >= 80 THEN
PRINT "The student is excellent."
ELSE
PRINT "The student passes."
END IF
ELSE
PRINT "The student failed."
END IF
In this example the outer IF checks passing, and the inner IF checks excellence. If the student passes, the program enters the inner IF; if not, it directly prints the failure information. Nested structures allow handling more complex logic.
Ambiguities can arise with nested if and else pairing. Consider:
if (x > 0)
if (y > 1)
z = 1;
else /* To which if does this else belong? */
z = 2;
According to C syntax, each else pairs with the nearest preceding if that lacks an else. So in the example above the else pairs with the inner if. To avoid ambiguity, always use braces. If the intent is for the else to pair with the outer if, write:
if (x > 0) {
if (y > 1)
z = 1;
}
else /* This else now belongs to the outer if */
z = 2;
A nested if structure allows more refined control by testing additional conditions inside an if block. For example:
if (condition1) {
// perform action 1
if (condition2) {
// perform action 2
}
}
Or nesting three levels:
if (condition1) {
// perform action 1
if (condition2) {
// perform action 2
if (condition3) {
// perform action 3
}
}
}
Nested ifs are one way to implement multiple branches. Comparing two numbers actually has three possibilities: equal, greater, or less. An if-else-if structure can represent this more clearly than deep nesting, so prefer using if-else-if for clarity. When using nested ifs, always bracket embedded blocks with '{' and '}' to improve readability and prevent mismatches between if and else.
3. switch
When multiple conditions are tested and many else clauses are required, the code can become long and hard to read. C provides the switch statement for multi-branch selection. If several tests depend on the value of the same variable, use switch instead of a long if-else-if chain.
Syntax:
switch (expression) {
case constant_expression_1:
statement_block1;
break;
case constant_expression_2:
statement_block2;
break;
case constant_expression_3:
statement_block3;
break;
...
default:
statement_blockN;
break;
}
The expression after switch must be an integer expression or a type that can be converted to int, such as char. Each case label must be a constant integral expression, typically characters or numbers.
Execution model: evaluate the switch expression, then compare the result with each case constant in order. When a matching case is found, execute statements from that case until a break is encountered. The break exits the switch. If no case matches, the default block is executed if provided. The default label is optional; if omitted and no case matches, the switch does nothing.
Notes when using switch:
- Case constant values must be distinct; duplicate values cause errors.
- Each case may contain multiple statements; braces are not required for the case block.
- The order of case clauses does not affect the result.
- The default clause can be omitted.
4. The ternary conditional operator
C also provides the conditional operator, a compact operator equivalent to if-else. It uses ? and : and takes three operands. Syntax:
expression1 ? expression2 : expression3
If expression1 evaluates to true (nonzero), the entire expression yields the value of expression2; otherwise it yields the value of expression3. The conditional operator is often used in assignment statements. For example, to get the maximum of two numbers:
max = num1 > num2 ? num1 : num2;
This checks num1 > num2; if true, max gets num1, otherwise max gets num2. The ternary expression is equivalent to:
if (expr1) {
expr2;
} else {
expr3;
}
Using the conditional operator for single assignments can make code more concise and sometimes improve efficiency.
Conditional operator exercise
Programming task: write a program that prompts the user to enter a base salary and calculates the after-tax salary. Personal income tax is applied only to the portion of salary exceeding 3500. Amounts less than or equal to 3500 are not taxed.
Program listing sample.c:
#include <stdio.h>
int main()
{
double sal;
double rate;
printf("Enter base salary: ");
// receive user input for base salary
scanf("%lf", &sal);
rate = (sal < 3500) ? 0 : 0.05;
// compute after-tax salary
sal = sal - (sal - 3500) * rate;
printf("\nNet salary after tax is: %7.2f\n", sal);
}
ALLPCB