The ‘default’ Keyword in C Programming

C Programming @ Freshers.in

In C programming, the ‘default’ keyword is a crucial component of switch statements. This article provides a comprehensive explanation of the ‘default’ keyword, its role in switch statements, and includes real-world examples to illustrate how it enhances code control and readability.

Understanding the ‘default’ Keyword

The ‘default’ keyword in C is used within switch statements to specify a code block that will be executed when none of the other case labels match the value of the expression. It serves as a fallback or default action when no specific case is satisfied.

Syntax for ‘default’ in a Switch Statement:

switch (expression) {
    case value_1:
        // Code for case value_1
        break;
    case value_2:
        // Code for case value_2
        break;
    // Additional cases...
    default:
        // Default code block executed when none of the cases match
}

Example 1: Using ‘default’ in a Switch Statement

#include <stdio.h>
int main() {
    int choice = 5;
    switch (choice) {
        case 1:
            printf("Option 1 selected\n");
            break;
        case 2:
            printf("Option 2 selected\n");
            break;
        default:
            printf("Invalid choice\n");
    }
    return 0;
}

Output:

Invalid choice

In this example, the value of choice is 5, which doesn’t match any of the case labels (1 or 2). Therefore, the code block associated with ‘default’ is executed, displaying “Invalid choice.”

Common Use Cases for ‘default’

  1. Fallback Handling: ‘default’ is used to handle cases not explicitly covered by other case labels, providing a fallback action.
  2. Error Handling: ‘default’ can be employed to handle unexpected or erroneous conditions within a switch statement.

Example 2: Using ‘default’ for Error Handling

#include <stdio.h>
int main() {
    int errorCode = 404;
    switch (errorCode) {
        case 200:
            printf("Success\n");
            break;
        case 404:
            printf("Resource not found\n");
            break;
        default:
            printf("Error: Unknown status code\n");
    }
    return 0;
}

Output:

Resource not found

In this example, the ‘default’ case is used to handle the scenario when the errorCode is not explicitly covered by other case labels.

Author: user