问题描述
if( (A) && (B) ) { //do something } else //do something else
问题是,如果A是假。 B甚至会得到评估?
The question is, would the statement immediately break to else if A was FALSE. Would B even get evaluated?
在这种情况下,当数组实际为空且有零个元素时,B检查数组索引的有效性为array [0]。因此,抛出一个segfault,因为我们试图访问超出数组的边界。
I ask this in the case that B checking the validity of an array index say array[0] when the array is actually empty and has zero elements. Therefore throwing a segfault because we are trying to access something that is out of bounds of the array. Specifically
if( (array.GetElements() > 0) && (array[0])) array[0]->doSomething(); else //do nothing and return
[0]实际上得到评估,因为它在没有第一个检查到'&&'左侧的segfaults。 Precedence告诉我,左侧肯定会优先,但它不告诉我,如果左侧是FALSE它不会评估右侧。
This may be dangerous if array[0] actually gets evaluated because it segfaults without the first check to the left of the '&&'. Precedence tells me that the left side will definitely take precedence but it doesn't tell me that it won't evaluate the right side if the left is FALSE.
推荐答案
在C和C ++中,&& 和 || 电路。这意味着它们只在需要时评估参数。如果&& 的第一个参数为false,或者第一个参数为 ||
In C and C++, the && and || operators "short-circuit". That means that they only evaluate a parameter if required. If the first parameter to && is false, or the first to || is true, the rest will not be evaluated.
您发布的代码是安全的,但我怀疑为什么要包含一个空的 else 块。
The code you posted is safe, though I question why you'd include an empty else block.
这篇关于如何评估“if(A&& B)”语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!