当前位置: 首页 > 面试题库 >

If和Else If之间的区别?

谭向晨
2023-03-14
问题内容

我想知道为什么要使用一个else if语句而不是多个if语句?例如,这样做之间有什么区别:

if(i == 0) ...
else if(i == 1) ...
else if(i == 2) ...

还有这个:

if(i == 0) ...
if(i == 1) ...
if(i == 2) ...

他们似乎做的完全一样。


问题答案:
if(i == 0) ... //if i = 0 this will work and skip following statement
else if(i == 1) ...//if i not equal to 0 and if i = 1 this will work and skip following statement
else if(i == 2) ...// if i not equal to 0 or 1 and if i = 2 the statement will execute


if(i == 0) ...//if i = 0 this will work and check the following conditions also
if(i == 1) ...//regardless of the i == 0 check, this if condition is checked
if(i == 2) ...//regardless of the i == 0 and i == 1 check, this if condition is checked


 类似资料:
  • 问题内容: 两者之间有什么区别吗? …和… ? 问题答案: 它们是相同的,但是如果您的代码中包含MVC并且不想在代码中产生大量回声,那么第二个方法就很棒。例如,在我的文件(Zend Framework)中,我将编写如下内容:

  • 本文向大家介绍if-else和switch之间的区别,包括了if-else和switch之间的区别的使用技巧和注意事项,需要的朋友参考一下 在本文中,我们将了解if-else语句和'switch'语句之间的区别。 if-else 根据语句中的表达式,将生成输出。 它对多个选择使用多个语句。 该语句测试是否相等。 它可以用来测试逻辑表达式。 它可以计算整数,字符,指针,浮点类型和布尔类型。 仅执行“

  • if statements in Smarty have much the same flexibility as php if statements, with a few added features for the . Everyif must be paired with an/if .else andelseif are also permitted. "eq", "ne","neq",

  • 概要 <#if condition> ... <#elseif condition2> ... <#elseif condition3> ... ... <#else> ... </#if> 这里: condition, condition2, 等:将被计算成布尔值的表达式。 elseif 和 else 是可选的。 描述 你可以使用 if, elseif 和 else 指令来条

  • 问题内容: 给定以下代码段,有什么明显的区别? 与 还是单出口原则在这段代码中会更好… 有没有明显的性能差异?您是否觉得其中一个比另一个更可维护/可读? 问题答案: 在第二个示例中,您非常清楚地指出两个条件是互斥的。 对于第一个,并不清楚,并且在(不太可能)的事件中,在两个if之间添加to的分配,逻辑将发生变化。 假设将来有人在第二个if之前添加。 当然,这不太可能发生,但是如果我们在这里谈论可维

  • 一个If语句后面跟着一个或多个ElseIf语句,这些语句由布尔表达式组成,然后是一个默认的else语句,当所有条件都变为false时执行。 语法 (Syntax) 以下是VBScript中If Elseif - Else语句的语法。 If(boolean_expression) Then Statement 1 ..... ..... Statement n ElseIf