Efficient way to escaping the if-else in C

The following selection statement supports by C programming language.

if ( expression ) 
   secondary-block
 

   
    
if ( expression ) 
    secondary-block 
else 
    secondary-block




switch ( expression ) 
       secondary-block

 

In C, a selection statement selects among a set of secondary blocks depending on the value of a controlling expression. That means if controlling expression false, then secondary blocks will be execute.

This blog post is not about the how to use the selection statements, but it is about to how to efficiently avoid the multi-if-else statements to promote clean and maintainable code.

Now are you thinking why you should remove the multi-if-else statements?

Don’t worry you will get the answer to your question automatically at the end of the article. There are several reasons to remove or reduce the usage of multi-if-else statements in your code. But here I want to mention few reasons to remove or reduce the usage of multi-if-else in your code. Here few of them:

Complexity: Nested and multi if-else statements increase the code complexity. This complexity can lead to bugs or unintended behaviors which sometimes are difficult to trace or debug.

Readability and Maintainability: C code that has excessive nesting of if-else statements are hard to read and understand. The readability of the code decreases with each new added condition.

Scalability and Testing Challenges: With each new condition code complexity is increases and a moment comes when adding or removing any exiting condition becomes the nightmare for the developers and testers. It requires a lot of testing efforts, and it might require writing several test cases to cover all possible scenarios. Also, if the UTC coverage and test suit for your code is not good, then it would be really nightmare.

Code Duplication: It is an also serious issue with multi if-else statements.

 

Strategies to avoid the usage of if-else statements:

Here are some strategies to escape or reduce the usage of if-else statements in your code. The below strategy is just my suggestion and might they not fit in all of the context. It would be totally your decision that which strategies is good for you.

1. Use switch statements:

You should use the switch case statement beside the using the chain of if-else statements when you have multiple conditions to check against a single variable. It will increase the code readability and maintainability.

switch (condition) //condition of a switch statement must be integer type
{
case value1:
    // code block
    break;

case value2:
    // code block
    break;
    
    // ... more cases
    
default:
    // default code block
    break;
}

 

2 Ternary Operator:

The ternary operator is a shorthand way to express an if-else statement. It takes three operands, that is why it is also called the ternary operator.

Its syntax is following,

condition_expression ? expression_1 : expression_2

Here expression1 will be evaluated if condition_expression evaluates to true; otherwise expression2 will be evaluated.

Consider the below example to see how ternary operator helps to avoid nested multiple if-else statement.

Grade calculation code using the if-else statement.

#include <stdio.h>

int main()
{
    char grade;
    int score;

    printf("Enter the score: ");
    scanf("%d",&score);


    if (score >= 90)
    {
        grade = 'A';
    }
    else if (score >= 80)
    {
        grade = 'B';
    }
    else if (score >= 70)
    {
        grade = 'C';
    }
    else if (score >= 60)
    {
        grade = 'D';
    }
    else
    {
        grade = 'F';
    }

    printf("Your grade is: %c\n", grade);
    return 0;
}

Output:

Enter the score: 91
Your grade is: A

 

Grade calculation code using the ternary operator.

/**
 C Program to find grade using
 ternary operator.
*/

#include <stdio.h>

int main()
{
    int score;

    printf("Enter the score: ");
    scanf("%d",&score);

    const char grade = (score >= 90) ? 'A'
                       : (score >= 80) ? 'B'
                       : (score >= 70) ? 'C'
                       : (score >= 60) ? 'D'
                       : 'F';

    printf("Your grade is: %c\n", grade);
    return 0;
}

 

3 Lookup Tables:

A lookup tables also helps to avoid the branching statements. If the count of possible inputs and corresponding outputs is limited, then you can use the lookup table.

For better understanding consider the below C program to enter weekdays number and print day name of week.

Using the multi if-else statement,

/*
C program to enter week number and print day name of week
*/ #include <stdio.h> int main() { unsigned int daysOfWeek; //Ask user to input week number printf("Enter days number (1-7): "); scanf("%u", &daysOfWeek); if(daysOfWeek == 1) { printf("Monday\n"); } else if(daysOfWeek == 2) { printf("Tuesday\n"); } else if(daysOfWeek == 3) { printf("Wednesday\n"); } else if(daysOfWeek == 4) { printf("Thursday\n"); } else if(daysOfWeek == 5) { printf("Friday\n"); } else if(daysOfWeek == 6) { printf("Saturday\n"); } else if(daysOfWeek == 7) { printf("Sunday\n"); } else { printf("Invalid Input! Please enter week number between 1-7.\n"); } return 0; }

Output:

Enter days number (1-7): 4
Thursday

 

Using the lookup table,

/*
C program to enter week number and print day name of week
*/ #include <stdio.h> const char* getDayName(int index) { // Default value if index is out of range char *pName = "Invalid day"; //lookup-table char * daysOfWeek[] = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" }; //prevent from go beyond array boundary if(index > 0 && index < 8) { pName = daysOfWeek[index-1]; } return pName; } int main() { unsigned int dayIndex; //Ask user to input week number printf("Enter week number (1-7): "); scanf("%u", &dayIndex); // Print week name using array index printf("%s", getDayName(dayIndex)); return 0; }

Output:

Enter days number (1-7): 4
Thursday

 

4 Refactor into Small Functions:

Break down a complex and big function into a smaller and less complex function. This technique not only helps you to reduce the count of if-else statement but also makes the code more modular, readable and maintainable.

Consider the below code where function pointers or a lookup table to determine the name of days. But I believe it is not a best example to solve the multi if-else with the help of refactor a function, but I helps you to visualize that how you can solve the problem.

#include <stdio.h>

typedef char* (*pDaysName)();

char* day1()
{
    return "Monday";
}

char* day2()
{
    return "Tuesday";
}

char* day3()
{
    return "Wednesday";
}

char* day4()
{
    return "Thursday";
}

char* day5()
{
    return "Friday";
}

char* day6()
{
    return "Saturday";
}

char* day7()
{
    return "Sunday";
}


// Function to get grade based on score range
char* getDaysName(int dayIndex)
{
    pDaysName daysName[] = {day1, day2, day3, day4,
                            day5, day6, day7
                           };

    if (dayIndex >= 1 && dayIndex <= 7)
    {
        return daysName[dayIndex-1]();
    }
    else
    {
        return "Invalid Date";
    }
}

int main()
{
    unsigned int dayIndex;

    //Ask user to input week number
    printf("Enter days number (1-7): ");
    scanf("%u", &dayIndex);

    const char *name = getDaysName(dayIndex);

    printf("Your grade is: %s\n", name);
    return 0;
}

 

 

Recommended posts for you:

Leave a Reply

Your email address will not be published. Required fields are marked *