Is there any difference between using multiple if statements and else if statements?

后端 未结 4 525
情深已故
情深已故 2021-02-01 14:46

This question pertains specifically to shell scripts, but could be about any programming language.

Is there any difference between using multiple if stateme

4条回答
  •  无人及你
    2021-02-01 15:06

    Yes, potentially. Consider this (C#, Java, whatever):

    int x = GetValueFromSomewhere();
    
    if (x == 0)
    {
        // Something
        x = 1;
    }
    else if (x == 1)
    {
        // Something else...
    }
    

    vs this:

    int x = GetValueFromSomewhere();
    
    if (x == 0)
    {
        // Something
        x = 1;
    }
    if (x == 1)
    {
        // Something else...
    }
    

    In the first case, only one of "Something" or "Something else..." will occur. In the second case, the side-effects of the first block make the condition in the second block true.

    Then for another example, the conditions may not be mutually exclusive to start with:

    int x = ...;
    
    if (x < 10)
    {
        ...
    } 
    else if (x < 100)
    {
        ...
    }
    else if (x < 1000)
    {
        ...
    }
    

    If you get rid of the "else" here, then as soon as one condition has matched, the rest will too.

提交回复
热议问题