c
  1. c-if-else-vs-switch

C if-else vs switch Statements

Explanation

C provides two primary conditional statements for evaluating a set of conditions and executing appropriate code blocks: if-else and switch. The if-else statement evaluates a set of conditions and executes a block of code if the condition is true, while the switch statement evaluates a variable or expression against a set of values and executes a block of code for each matching value.

Syntax

If-Else

if (condition) {
  // code block to execute if condition is true
} else {
  // code block to execute if condition is false
}

Switch

switch (expression) {
  case value1:
    // code block to execute if expression equals value1
    break;
  case value2:
    // code block to execute if expression equals value2
    break;
  default:
    // code block to execute if expression is not equal to any case
}

Example

If-Else

#include <stdio.h>
int main() {
   int num = 3;
   if(num == 1) {
      printf("Number is 1");
   } else if(num == 2) {
      printf("Number is 2");
   } else {
      printf("Number is not 1 or 2");
   }
   return 0;
}

Switch

#include <stdio.h>
int main() {
   int num = 3;
   switch(num) {
      case 1:
         printf("Number is 1");
         break;
      case 2:
         printf("Number is 2");
         break;
      default:
         printf("Number is not 1 or 2");
   }
   return 0;
}

Output

The output for both examples will be:

Number is not 1 or 2

Use

The if-else statement is a powerful tool for evaluating a range of conditions based on a single expression. It provides greater flexibility and allows for the use of logical operators to combine multiple conditions. The switch statement is useful when there is a clear set of values to be evaluated, such as when working with enums or simple integer values.

Important Points

  • The if-else statement is used for evaluating a set of conditions and executing code based on their outcome.
  • The switch statement is used for evaluating a single expression against a set of possible values and executing code for each match.
  • The break statement is used to exit the switch statement, preventing execution of subsequent cases.
  • The default case is executed if none of the cases match the expression being evaluated.

Summary

The if-else and switch statements are essential tools for conditional programming in C. Understanding their syntax, use cases, and important points can greatly enhance your ability to write concise and effective code. While if-else is generally more flexible and appropriate for evaluating complex conditions, switch is useful for working with a well-defined set of values. Knowing when to use each statement can speed up your programming and lead to more maintainable code.

Published on: