🔀 switch in C

🔀 switch Statement in C

🔍 Short Explanation:
The switch statement in C is used to perform different actions based on the value of a variable or expression. It's ideal for handling multiple fixed conditions cleanly.


✅ Syntax

switch (expression) {
    case constant1:
        // code block
        break;
    case constant2:
        // code block
        break;
    ...
    default:
        // optional block
}
  

📋 Example

#include <stdio.h>

int main() {
    int day = 3;

    switch (day) {
        case 1:
            printf("Monday\\n");
            break;
        case 2:
            printf("Tuesday\\n");
            break;
        case 3:
            printf("Wednesday\\n");
            break;
        default:
            printf("Invalid day\\n");
    }

    return 0;
}
  

🧠 Output: Wednesday

💡 Common Use Cases

  • Menu-based programs
  • Day/month selection
  • Character or integer options

⚠️ Tips & Mistakes to Avoid

  • Don’t forget break; to prevent fall-through
  • Each case must use a constant or literal value
  • Use default to handle unexpected values

📌 Summary

The switch statement is a cleaner alternative to multiple if-else checks. It's best used when evaluating one variable against many fixed options.


Keywords: switch statement in c, c switch case, how to use switch in c, switch example c language, c programming decision making Tags: c programming, switch case, control statement, beginner tutorial, c language examples

একটি মন্তব্য পোস্ট করুন