[c++] How an 'if (A && B)' statement is evaluated?

if( (A) && (B) )
{
  //do something
}
else
  //do something else

The question is, would the statement immediately break to else if A was FALSE. Would B even get evaluated?

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

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.

This question is related to c++

The answer is


yes, if( (A) && (B) ) will fail on the first clause, if (A) evaluates false.

this applies to any language btw, not just C derivatives. For threaded and parallel processing this is a different story ;)


for logical && both the parameters must be true , then it ll be entered in if {} clock otherwise it ll execute else {}. for logical || one of parameter or condition is true is sufficient to execute if {}.

if( (A) && (B) ){
     //if A and B both are true
}else{
}
if( (A) ||(B) ){
     //if A or B is true 
}else{
}

You are asking about the && operator, not the if statement.

&& short-circuits, meaning that if while working it meets a condition which results in only one answer, it will stop working and use that answer.

So, 0 && x will execute 0, then terminate because there is no way for the expression to evaluate non-zero regardless of what is the second parameter to &&.


Yes, it is called Short-circuit Evaluation.

If the validity of the boolean statement can be assured after part of the statement, the rest is not evaluated.

This is very important when some of the statements have side-effects.