Short circuit behavior of logical operators

suggest change

Short-circuit evaluation skips the rest of a condition in if, while, and similar statements when the result is already known. For &&, the second operand is not evaluated when the first compares equal to 0. For ||, it is not evaluated when the first compares unequal to 0. The bitwise operators & and | do not short-circuit.

Example:

#include <stdio.h>
 
int main(void) {
  int a = 20;
  int b = -5;
 
  /* 'b == -5' is not evaluated, because 'a != 20' is false. */
  if (a != 20 && b == -5) {
    printf("I won't be printed!\n");
  }
   
  return 0;
}

Check it out yourself:

#include <stdio.h>

int print(int i) {
 printf("print function %d\n", i);
 return i;
}

int main(void) {
 int a = 20;

 /* 'print(a)' is not called, because 'a != 20' is false. */
 if (a != 20 && print(a)) {
   printf("I won't be printed!\n");
 }

 /* 'print(a)' is called, because 'a == 20' is true. */
 if (a == 20 && print(a)) {
   printf("I will be printed!\n");
 }

 return 0;
}
print function 20
I will be printed!

Short-circuit evaluation matters when a later operand is expensive or would be undefined if the earlier test failed, as with p != NULL && *p == 1. It also changes control flow. A classic case is a program that prints forked more times than a straight reading of the source suggests: http://stackoverflow.com/questions/26716255/why-does-this-program-print-forked-4-times.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents