-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'

  • 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 '15 at 18:07
  • 1
    If condition 1 fails , second will never be checked for &&. And loop will exit – SacJn Oct 20 '15 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 '15 at 18:10
  • Why java tag? Java has no notion of pointer – Amadeus Oct 20 '15 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 '15 at 18:12

3 Answers3

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.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
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.

BlackHatSamurai
  • 23,275
  • 22
  • 95
  • 156
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.

sparkhee93
  • 1,381
  • 3
  • 21
  • 30