This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

what is the use of default in switch-case?

what is the use of default in switch-case?

Parents Reply Children
  • Entering the default clause in a state machine (where the switch variable is normally an enumerator) should preferably be coded to represent an error.

    But a switch statement is used for way more than just state machines.

    When decoding charactesr in a parser, you may have:

    switch (ch) {
        case '(': do_lparen(); break;
        case ')': do_rparen(); break;
        case '+': do_add(); break;
        ...
        default:
            if (ch >= 'a' && ch <= 'z'
            ||  ch >= 'A' && ch <= 'Z') {
                do_alpha(ch);
            } else if (ch >= '0' && ch <= '9') {
                do_digit(ch);
            } else {
                invalid_character(ch);
            }
    }