Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Syntax Question

Is it considered bad coding to put a break in the default part of a switch statement? A book I was reading said that it was optional but the teacher counted off for using it.

like image 955
shinjuo Avatar asked Nov 27 '22 03:11

shinjuo


2 Answers

Best practice is to always use a break unless you mean for control to flow into another case, even at the end of the switch.

like image 58
Ned Batchelder Avatar answered Jan 13 '23 02:01

Ned Batchelder


It depends if you have it at the start or the end of the switch statement. If there are other cases after the default then you probably do want a break there unless you really want to fall through.

switch (a)
{
    case 0:
    default:
        printf("Default\n");
        break;

    case 1:
        printf("1\n");
        break;

    case 2:
        printf("2\n");
        break;
}
like image 26
Graham Borland Avatar answered Jan 13 '23 02:01

Graham Borland