Example 1 — Short-circuit evaluation
A function with a side effect shows whether the right operand ran.
#include <stdio.h>
static int calls = 0;
static int check(void) {
calls++;
return 1;
}
int main(void) {
int a = 0;
if (a != 0 && check()) { }
printf("after false &&: calls = %d\n", calls);
if (a == 0 && check()) { }
printf("after true &&: calls = %d\n", calls);
if (a == 0 || check()) { }
printf("after true ||: calls = %d\n", calls);
return 0;
} How It Works
a != 0is false, socheck()never runs.a == 0is true, so&&must evaluatecheck().- For
||, a true left side makes the right side unnecessary.
