使用多个if语句和if语句之间有什么区别吗? [英] Is there any difference between using multiple if statements and else if statements?

查看:182
本文介绍了使用多个if语句和if语句之间有什么区别吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题专门针对shell脚本,但可能与任何编程语言有关。

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

使用多个之间是否存在任何差异语句并在shell脚本中使用 elif 语句?并且, case 语句在我的情况下不起作用。

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.

推荐答案

是的,可能。考虑这个(C#,Java,等等):

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...
}

在第一种情况下,只会出现一个的Something或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.

这篇关于使用多个if语句和if语句之间有什么区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆