Switch statement with returns — code correctness

前端 未结 17 2220
梦如初夏
梦如初夏 2020-12-12 20:05

Let\'s say I have code in C with approximately this structure:

switch (something)
{
    case 0:
      return \"blah\";
      break;

    case 1:
    case 4:
         


        
17条回答
  •  南笙
    南笙 (楼主)
    2020-12-12 20:42

    I personally tend to lose the breaks. Possibly one source of this habit is from programming window procedures for Windows apps:

    LRESULT WindowProc (HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
    {
        switch (uMsg)
        {
            case WM_SIZE:
                return sizeHandler (...);
            case WM_DESTROY:
                return destroyHandler (...);
            ...
        }
    
        return DefWindowProc(hwnd, uMsg, wParam, lParam);
    }
    

    I personally find this approach a lot simpler, succinct and flexible than declaring a return variable set by each handler, then returning it at the end. Given this approach, the breaks are redundant and therefore should go - they serve no useful purpose (syntactically or IMO visually) and only bloat the code.

提交回复
热议问题