C default case

Created By: chatGPT

In C, the switch statement provides a way to execute different pieces of code based on the value of a variable. Within a switch statement, we can use case labels to specify different actions for specific values. The default case is a special case that can be used to handle scenarios not explicitly mentioned by the case statements. It is executed when none of the specified case labels match the value of the expression evaluated in the switch.
switch (variable) {
    case value1:
        // code to execute for value1
        break;
    case value2:
        // code to execute for value2
        break;
    default:
        // code to execute if no case matches
        break;
}
To ensure the default case is executed when there are no matches, you simply add it at the end of your switch statement. It's a good practice to include a break; statement after the default case as well, although it's not strictly necessary if it is the last case in the switch.
switch (input) {
    case 1:
        printf("Option 1 selected\n");
        break;
    case 2:
        printf("Option 2 selected\n");
        break;
    default:
        printf("Invalid option\n");
        break;
}
If you use a switch statement without a default case and the expression does not match any of the cases, nothing will happen. If the input matches any of the cases, the corresponding block of code will execute. Including a default case is essential for handling unexpected values gracefully.
// Example of using switch with default case
#include <stdio.h>

int main() {
    int option = 3;
    switch (option) {
        case 1:
            printf("You chose option 1.\n");
            break;
        case 2:
            printf("You chose option 2.\n");
            break;
        default:
            printf("Invalid option selected.\n");
    }
    return 0;
}
Introduction And SetupVariablesData TypesIntFloatDoubleCharVoidUnsignedSignedConstantsEnumerationsArraysStringsStructsUnionsTypedefsPointersDynamic Memory AllocationMallocCallocReallocFreeFunctionsFunction DeclarationsFunction DefinitionsFunction CallsReturn StatementInline FunctionsRecursionHeader FilesPreprocessor DirectivesControl FlowIf StatementElse StatementElse If StatementSwitch StatementCase StatementDefault CaseLoopsFor LoopWhile LoopDo While LoopBreak StatementContinue StatementGoto StatementLabelsOperatorsArithmetic OperatorsRelational OperatorsLogical OperatorsBitwise OperatorsAssignment OperatorsConditional (ternary) OperatorComma OperatorSizeof OperatorData StructuresLinked ListsStacksQueuesTreesGraphsFunction PointersCallbacksMacrosCommentsSingle Line CommentsMulti Line CommentsSyntaxSyntax ErrorsCompilation ErrorsDebuggingStandard Input OutputPrintfScanfFile HandlingFopenFcloseFreadFwriteFprintfFgetsFputsError HandlingErrnoAssertionsExit FunctionExit CodesEvent HandlingSignal HandlingInterrupts