Does case-switch work like this?

前端 未结 5 525
广开言路
广开言路 2020-11-30 09:45

I came across a case-switch piece of code today and was a bit surprised to see how it worked. The code was:

switch (blah)
{
case a:
  break;
case b:
  break;         


        
5条回答
  •  温柔的废话
    2020-11-30 09:52

    This is called a fall-through.

    It is exactly doing what you are seeing: several cases is going to execute same piece of code.

    It is also convenient in doing extra processing for certain case, and some shared logic:

    // psuedo code:
    void stopServer() {
        switch (serverStatus)
        case STARTING:
        {
            extraCleanUpForStartingServer();
            // fall-thru
        }
        case STARTED:
        {
            deallocateResources();
            serverStatus = STOPPED;
            break;
        }
        case STOPPING:
        case STOPPED:
        default:
            // ignored
            break;
    }
    

    This is a typical use of fall-through in switch-case. In case of STARTING and STARTED, we need to do deallocateResources and change the status to STOPPED, but STARTING need some extra cleanup. By the above way, you can clearly present the 'common logic' plus extra logic in STARTING.

    STOPPED, STOPPING and default are similar, all of them fall thru to default logic (which is ignoring).

    It is not always a good way to code like this but if it is well used it can present the logic better.

提交回复
热议问题