break in a case with return.. and for default

前端 未结 13 1990
予麋鹿
予麋鹿 2020-12-11 14:19

My OCD makes me add \"break\" when writing case statements, even if they will not be executed. Consider the following code example:

switch(option) {
    cas         


        
相关标签:
13条回答
  • 2020-12-11 15:09

    I would consider the break after return to be bad form, you will get warnings about unreachable code on some compilers.

    The break on your default case is completely appropriate, case fall through is a tool and should be especially marked when used.

    0 讨论(0)
  • 2020-12-11 15:12

    I don't personally put the breaks in, but it could help when someone else decides to move the return (-1) to outside of the switch and forgets to add break.

    0 讨论(0)
  • 2020-12-11 15:13

    The break after your default case is just a matter of personal preference.

    Putting a break after return almost seems contradictory to me. I'd remove the break, just to make the return statement really stand out.

    0 讨论(0)
  • 2020-12-11 15:13

    Neither break does anything for you, but neither does harm.

    Personally, I usually leave them out if I have a return - but I also try to avoid having multiple return points in a function if possible.

    However, I do think the break in the default: case is good - for one reason: If you were to leave it out, and somebody added a new case after default:, the behavior would be different if they "forget" to add in a break.

    0 讨论(0)
  • 2020-12-11 15:13

    Regarding the comment that others have made that they leave the break in the default case in case someone comes by later and adds a case after it: Where I work, the coding standard says to always put the default as the last case; so in our situation, a break on that case is just redundant. (This is one case where I agree wholeheartedly with the company's coding standard, because with the default case always being the last one, you always know where to find it, even in a long switch-statement.)

    As for breaks after returns, I tend to omit the break unless there are any execution paths that do not return, as I find it redundant. (My exception to this is, on the rare occasions when there are several execution paths in a case and I can't tell with a quick scan of the code whether or not they all return, then I'll leave the break in just to be safe.)

    0 讨论(0)
  • 2020-12-11 15:17

    I would put the break in to show that you do not intend to fall through to next case.

    0 讨论(0)
提交回复
热议问题