Short Circuiting

R has two types of logical operators: vectorized operators & and |, and short-circuiting operators && and ||. Short-circuiting operators are used when you want to evaluate only the first element of a logical expression, which is common in control flow statements.

# Short Circuiting example
x <- TRUE
y <- FALSE
if (x && y) {
    print("Both x and y are TRUE")
} else {
    print("At least one of x or y is FALSE")
}

Output:

[1] "At least one of x or y is FALSE"

Code Explanation: The short-circuiting AND operator && only evaluates the first element of each logical expression. Since y is FALSE, the expression x && y evaluates to FALSE, and the else block is executed.

Key Takeaways

  • Use && and || for short-circuit evaluation in control flow.
  • Short-circuiting can improve performance by not evaluating unnecessary expressions.
  • Short-circuiting operators are commonly used in if statements to control logical flow.