-1
While (condition-1 && condition-2) {
   // Do something
}

Assume that if condition-1 fails, condition-2 can potentially cause a segmentation fault. So, does the loop exit as soon as condition-1 fails before even checking for condition-2 or does it check it anyway, making this practice unsafe?

Ex: Condition-1 may be 'Node* temp != 0' and condition-2 can be 'temp->next != int i'

5
  • 1
    If condition 1 fails, condition 2 will not be checked, because of the AND. Upon encountering a "FALSE", nothing could happen to make the condition TRUE
    – CubeJockey
    Oct 20, 2015 at 18:07
  • 1
    If condition 1 fails , second will never be checked for &&. And loop will exit
    – SacJn
    Oct 20, 2015 at 18:07
  • Will the second condition not be checked in the first one failed if the && were to be replaced by ||?
    – Chanakya
    Oct 20, 2015 at 18:10
  • Why java tag? Java has no notion of pointer
    – Amadeus
    Oct 20, 2015 at 18:11
  • If you're using a ||, both conditions could be checked. For the same reasons above, as long as there remains the possibility of a TRUE evaluation, conditions will continue to be checked. When using OR, the second condition may yet be TRUE even if the first isn't. If the first condition is TRUE, the second won't be checked.
    – CubeJockey
    Oct 20, 2015 at 18:12

3 Answers 3

3

If condition-1 is false then there is no reason to check the other condition as false && anything will still be false. This is called Short Circuit Evaluation.

Conversely if we had

While (condition-1 || condition-2) {
   // Do something
}

and condition-1 == true then we will never check condition-2 as true || anything is still true.

0

Considering that you are using the && operand, the second condition will never be checked, as there is not chance that the collective condition will ever be true.

0

&& is a conditional statement will check the first condition and if it's true, it will check the second condition. But if it's false, it'll exit the loop without checking the second condition.

2
  • 1
    & is a bitwise logical (arithmetic) operator, not a boolean operator.
    – rici
    Oct 20, 2015 at 18:18
  • Ah you're right, sorry about that.
    – sparkhee93
    Oct 20, 2015 at 18:19

Not the answer you're looking for? Browse other questions tagged or ask your own question.