Site icon R-bloggers

Understanding Switch Statements in C Programming

[This article was first published on Steve's Data Tips and Tricks, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
< section id="what-is-a-switch-statement" class="level1">

What is a Switch Statement?

A switch statement is a powerful control flow mechanism in C programming that allows you to execute different code blocks based on the value of a single expression. It provides a more elegant and efficient alternative to long chains of if-else statements when you need to compare a variable against multiple possible values.

< section id="basic-syntax-of-switch-statement" class="level1">

Basic Syntax of Switch Statement

switch (expression) {
    case constant1:
        // code block 1
        break;
    case constant2:
        // code block 2
        break;
    default:
        // default code block
        break;
}
< section id="how-switch-statements-work" class="level1">

How Switch Statements Work

The execution of a switch statement follows a specific pattern:

  1. The expression in parentheses is evaluated once
  2. The value is compared with each case constant
  3. If a match is found, the corresponding code block executes
  4. The break statement exits the switch structure
  5. If no match is found, the default case executes (if present)
< section id="advantages-of-using-switch-statements" class="level1">

Advantages of Using Switch Statements

< section id="common-use-cases" class="level1">

Common Use Cases

Switch statements are particularly useful in several scenarios:

Let’s look at a practical example of a menu-driven program:

#include <stdio.h>

int main() {
    int choice;
    
    printf("Select an option:\n");
    printf("1. View balance\n");
    printf("2. Deposit money\n");
    printf("3. Withdraw money\n");
    printf("4. Exit\n");
    
    scanf("%d", &choice);
    
    switch(choice) {
        case 1:
            printf("Your balance is $1000\n");
            break;
        case 2:
            printf("Enter amount to deposit\n");
            break;
        case 3:
            printf("Enter amount to withdraw\n");
            break;
        case 4:
            printf("Thank you for using our service\n");
            break;
        default:
            printf("Invalid option\n");
    }
    
    return 0;
}

Output from my Terminal
< section id="rules-and-limitations" class="level1">

Rules and Limitations

  1. The switch expression must evaluate to an integral type (int, char, short, long)
  2. Case labels must be compile-time constants
  3. Case labels must be unique
  4. The default case is optional
  5. Multiple statements per case are allowed
< section id="best-practices" class="level1">

Best Practices

  1. Always include a default case
  2. Use break statements consistently
  3. Group related cases together
  4. Keep case blocks short and focused
  5. Use meaningful constants or enums for case labels
< section id="common-mistakes-to-avoid" class="level1">

Common Mistakes to Avoid

  1. Forgetting break statements
  2. Using non-constant case labels
  3. Attempting to use floating-point numbers
  4. Duplicate case values
  5. Complex expressions in case statements
< section id="switch-statement-examples" class="level1">

Switch Statement Examples

< section id="basic-example" class="level2">

Basic Example

#include <stdio.h>

int main() {
    char grade = 'B';
    
    switch(grade) {
        case 'A':
            printf("Excellent!\n");
            break;
        case 'B':
            printf("Good job!\n");
            break;
        case 'C':
            printf("Fair result\n");
            break;
        case 'F':
            printf("Try again\n");
            break;
        default:
            printf("Invalid grade\n");
    }
    
    return 0;
}
< section id="multiple-cases-example" class="level2">

Multiple Cases Example

#include <stdio.h>

int main() {
    int day = 2;
    
    switch(day) {
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
            printf("Weekday\n");
            break;
        case 6:
        case 7:
            printf("Weekend\n");
            break;
        default:
            printf("Invalid day\n");
    }
    
    return 0;
}
< section id="your-turn" class="level1">

Your Turn!

Try solving this problem:

Create a switch statement that converts a number (1-12) to the corresponding month name.

< details> < summary> Click to see the solution

Here’s the solution:

#include <stdio.h>

int main() {
    int month = 3;
    
    switch(month) {
        case 1: printf("January\n"); break;
        case 2: printf("February\n"); break;
        case 3: printf("March\n"); break;
        case 4: printf("April\n"); break;
        case 5: printf("May\n"); break;
        case 6: printf("June\n"); break;
        case 7: printf("July\n"); break;
        case 8: printf("August\n"); break;
        case 9: printf("September\n"); break;
        case 10: printf("October\n"); break;
        case 11: printf("November\n"); break;
        case 12: printf("December\n"); break;
        default: printf("Invalid month\n");
    }
    
    return 0;
}
< section id="quick-takeaways" class="level1">

Quick Takeaways

< section id="faqs" class="level1">

FAQs

  1. Q: Can I use strings in switch statements? A: No, C switch statements only work with integral types.

  2. Q: What happens if I forget a break statement? A: The code will “fall through” to the next case, executing all subsequent cases until a break is encountered.

  3. Q: Can I use variables as case labels? A: No, case labels must be compile-time constants.

  4. Q: Is switch faster than if-else? A: Generally yes, especially when dealing with multiple conditions.

  5. Q: Can I use multiple default cases? A: No, only one default case is allowed per switch statement.

< section id="references" class="level1">

References

  1. GeeksForGeeks. (2024). “Switch Statement in C”(https://www.geeksforgeeks.org/c-switch-statement/)

  2. TutorialsPoint. (2024). “Switch Statement in C Programming”(https://www.tutorialspoint.com/cprogramming/switch_statement_in_c.htm)

  3. Programiz. (2024). “C switch case Statement”(https://www.programiz.com/c-programming/c-switch-case-statement)

We’d love to hear about your experiences with switch statements! Share your thoughts and questions in the comments below, and don’t forget to share this guide with fellow C programming enthusiasts!


Happy Coding! 🚀

Switch Statement in C

You can connect with me at any one of the below:

Telegram Channel here: https://t.me/steveondata

LinkedIn Network here: https://www.linkedin.com/in/spsanderson/

Mastadon Social here: https://mstdn.social/@stevensanderson

RStats Network here: https://rstats.me/@spsanderson

GitHub Network here: https://github.com/spsanderson

Bluesky Network here: https://bsky.app/profile/spsanderson.com


To leave a comment for the author, please follow the link and comment on their blog: Steve's Data Tips and Tricks.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Exit mobile version