Back to TILs

C++ short_circuit

Date: 2023-02-22Last modified: 2024-11-02

Table of contents

bool car() {
  fmt::print("   car function running\n");
  return true;
}

bool house() {
  fmt::print(" house function running\n");
  return false;
}

bool job() {
  fmt::print("   job function running\n");
  return true;
}

bool spouse() {
  fmt::print("spouse function running\n");
  return true;
}

int main([[maybe_unused]] int argc, [[maybe_unused]] char **argv) {
  // First FALSE abort execution of AND
  //    T        F           T          T
  if (car() and house() and job() and spouse()) {
    fmt::print("I am happy AND!\n");
  } else {
    fmt::print("I am sad AND!\n");
  }
  fmt::print("=================\n");
  //    T        T          T            F
  if (car() and job() and spouse() and house()) {
    fmt::print("I am happy AND!\n");
  } else {
    fmt::print("I am sad AND!\n");
  }
  fmt::print("=================\n");

  // First TRUE abort execution of OR
  //    T       T         T           F
  if (car() or job() or spouse() or house()) {
    fmt::print("I am happy OR!\n");
  } else {
    fmt::print("I am sad OR!\n");
  }

  return 0;
}

Possible output

   car function running
 house function running
I am sad AND!
=================
   car function running
   job function running
spouse function running
 house function running
I am sad AND!
=================
   car function running
I am happy OR!

References