执行顺序为,如果有多个条件语句 [英] Order of execution for an if with multiple conditionals

查看:111
本文介绍了执行顺序为,如果有多个条件语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在具有多个条件语句if语句,是如果第一结果是明确的执行的第二条件

In an if statement with multiple conditionals, is the second conditional executed if the outcome of the first is clear?

例如:

if(i>0 && array[i]==0){
}

如果我换了我的负值可能会出现段错误的条件语句,但这种方式没有发生段错误。我可以肯定地说这始终工作或确实有需要使用嵌套的if语句?

If I swap the conditionals a segfault may occur for negative values of i, but this way no segfault occurs. Can I be sure that this always works or do have have to use nested if statements?

推荐答案

这类型的评价被称为短路
一旦结果是100%的清楚,它不会继续评估。

This type of evaluation is called short-circuiting. Once the result is 100% clear, it does not continue evaluating.

这实际上是一个常见的​​编程技术。
例如,在C ++中,你经常会看到类似这样的:

This is actually a common programming technique. For example, in C++ you will often see something like:

if (pX!=null && pX->predicate()) { bla bla bla }

如果您更改条件的顺序,你可以调用一个空指针的方法和崩溃。当你有一个指向该结构在C A类似的例子将使用结构的领域。

If you changed the order of the conditions, you could be invoking a method on a null pointer and crashing. A similar example in C would use the field of a struct when you have a pointer to that struct.

您可以做类似的东西带或:

You could do something similar with or:

if(px==null || pX->isEmpty()} { bla bla bla }

这也是原因之一,这通常是一个好主意,以避免在if条件的副作用。

This is also one of the reasons that it is generally a good idea to avoid side effects in an if condition.

例如,假设你有:

if(x==4 && (++y>7) && z==9)

如果x为4,那么y将无论递增Z或y的值的,但是,如果它不是4,它不会在所有递增

If x is 4, then y will be incremented regardless of the value of z or y, but if it is not 4, it will not be incremented at all.

这篇关于执行顺序为,如果有多个条件语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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