How an 'if (A && B)' statement is evaluated?

后端 未结 5 464
野性不改
野性不改 2020-12-14 18:47
if( (A) && (B) )
{
  //do something
}
else
  //do something else

The question is, would the statement immediately break to else if A was FA

相关标签:
5条回答
  • 2020-12-14 19:05

    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.

    0 讨论(0)
  • 2020-12-14 19:10

    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.

    The code you posted is safe, though I question why you'd include an empty else block.

    0 讨论(0)
  • 2020-12-14 19:15

    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 ;)

    0 讨论(0)
  • 2020-12-14 19:17

    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{
    }
    
    0 讨论(0)
  • 2020-12-14 19:18

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

    0 讨论(0)
提交回复
热议问题