Is there any difference between using multiple if

2020-05-20 07:28发布

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

Is there any difference between using multiple if statements and using elif statements in shell scripts? And, a case statement would not work in my situation.

4条回答
相关推荐>>
2楼-- · 2020-05-20 07:54

When you have multiple if statements, each is evaluated separately, and if the conditions are right, the code in all of them might be executed. If you have if / elif statement, the second condition would be evaluated only after particular result of the evaluation of the first condition.

Consider this pseudocode:

If (cond A) { action 1}
If (cond B) { action 2}

If both cond A and cond B are true, both actions will execute.

On the other hand, this pseudocode:

If (cond A) {action 1}
Elif (cond B) {action 2}

Only one of the two actions (or neither) will be executed, no matter how both conditions evaluate.

查看更多
Deceive 欺骗
3楼-- · 2020-05-20 07:55

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.

查看更多
We Are One
4楼-- · 2020-05-20 07:58
if (x == 0) {
    // 1
}


if (x >= 0) {
    // 2
}

if (x <= 0) {
    // 3
}

Above code will produce different value than the code below for x=0.

if (x == 0) {
    // 1
} else if (x >= 0) {
    // 2
} else {
   // 3
}

In the first case all the statements 1, 2, and 3 will be executed for x = 0. In the second case only statements 1 will be.

查看更多
狗以群分
5楼-- · 2020-05-20 08:01

It has to do with efficiency and your needs. If statements are executed independent of one another; each one will run. Else if statements only execute if the previous ifs fail.

查看更多
登录 后发表回答