The short-circuit evaluation is performed with expressions containing any logical operators.
The logical AND and logical OR operators (&& and ||, respectively) exhibit "short-circuit" operation. That is, the second operand is not evaluated if the result can be deduced solely by evaluating the first operand. Show
Programmers should exercise caution if the second operand contains side effects because it may not be apparent whether the side effects actually occur. In the following code, the value of i is incremented only when i >= 0: enum { max = 15 }; int i = /* Initialize to user-supplied value */; if ( (i >= 0) && ( (i++) <= max) ) { /* Code */ } Although the behavior is well defined, it is not immediately obvious whether or not i gets incremented. Noncompliant Code ExampleIn this noncompliant code example, the second operand of the logical OR operator invokes a function that results in side effects: char *p = /* Initialize; may or may not be NULL */ if (p || (p = (char *) malloc(BUF_SIZE)) ) { /* Perform some computation based on p */ free(p); p = NULL; } else { /* Handle malloc() error */ return; } Because malloc() is called only if p is NULL when entering the if clause, free() might be called with a pointer to local data not allocated by malloc(). (See MEM34-C. Only free memory allocated dynamically.) This behavior is partially due to the uncertainty of whether or not malloc() is actually called. Compliant SolutionIn this compliant solution, a second pointer, q, is used to indicate whether malloc() is called; if not, q remains set to NULL. Passing NULL to free() is guaranteed to safely do nothing. char *p = /* Initialize; may or may not be NULL */ char *q = NULL; if (p == NULL) { q = (char *) malloc(BUF_SIZE); p = q; } if (p == NULL) { /* Handle malloc() error */ return; } /* Perform some computation based on p */ free(q); q = NULL; Risk AssessmentFailing to understand the short-circuit behavior of the logical OR or AND operator may cause unintended program behavior.
Automated DetectionRelated VulnerabilitiesSearch for vulnerabilities resulting from the violation of this rule on the CERT website.
With logical short-circuiting, the evaluation of logical expressions can terminate early once the result becomes fully determined. Due to the properties of logical AND and OR, the result of a logical expression is sometimes fully determined before evaluating all of the conditions:
When the evaluation of a logical expression terminates early by encountering one of these values, the expression is said to have short-circuited. Used properly, this technique enables you to perform complex comparisons efficiently in your code. For example, in the expression A && B, MATLAB does not evaluate condition B at all if condition A is false. Once it is determined that A is false, the value of B cannot change the outcome of the operation. Short-circuit evaluation, minimal evaluation, or McCarthy evaluation (after John McCarthy) is the semantics of some Boolean operators in some programming languages in which the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression: when the first argument of the AND function evaluates to false, the overall value must be false; and when the first argument of the OR function evaluates to true, the overall value must be true. In programming languages with lazy evaluation (Lisp, Perl, Haskell), the usual Boolean operators are short-circuit. In others (Ada, Java, Delphi), both short-circuit and standard Boolean operators are available. For some Boolean operations, like exclusive or (XOR), it is not possible to short-circuit, because both operands are always required to determine the result. Short-circuit operators are, in effect, control structures rather than simple arithmetic operators, as they are not strict. In imperative language terms (notably C and C++), where side effects are important, short-circuit operators introduce a sequence point – they completely evaluate the first argument, including any side effects, before (optionally) processing the second argument. ALGOL 68 used proceduring to achieve user-defined short-circuit operators and procedures. The use of short-circuit operators has been criticized as problematic:
Definition[edit]In any programming language that implements short-circuit evaluation, the expression x and y is equivalent to the conditional expression if x then y else x, and the expression x or y is equivalent to if x then x else y. In either case, x is only evaluated once. The generalized definition above accommodates loosely typed languages that have more than the two truth-values True and False, where short-circuit operators may return the last evaluated subexpression. This is called "last value" in the table below. For a strictly-typed language, the expression is simplified to if x then y else false and if x then true else y respectively for the boolean case. Precedence[edit]Although AND takes precedence over OR in many languages, this is not a universal property of short-circuit evaluation. An example of the two operator taking the same precedence and being left-associative with each other is POSIX shell's command-list syntax.[2]: §2.9.3 The following simple left-to-right evaluator enforces a precedence of AND over OR by a continue: function short-circuit-eval (operators, values) let result := True for each (op, val) in (operators, values): if op = "AND" && result = False continue else if op = "OR" && result = True return result else result := val return resultFormalization[edit]Short-circuit logic, with or without side-effects, have been formalized based on Hoare's conditional. A result is that non-short-circuiting operators can be defined out of short-circuit logic to have the same sequence of evaluation.[3] Support in common programming and scripting languages[edit]Boolean operators in various languages
1 ABAP and APL have no distinct boolean type. Common use[edit]Avoiding undesired side effects of the second argument[edit]Usual example, using a C-based language: int denom = 0; if (denom != 0 && num / denom) { ... // ensures that calculating num/denom never results in divide-by-zero error } Consider the following example: int a = 0; if (a != 0 && myfunc(b)) { do_something(); } In this example, short-circuit evaluation guarantees that myfunc(b) is never called. This is because a != 0 evaluates to false. This feature permits two useful programming constructs.
Both are illustrated in the following C snippet where minimal evaluation prevents both null pointer dereference and excess memory fetches: bool is_first_char_valid_alpha_unsafe(const char *p) { return isalpha(p[0]); // SEGFAULT highly possible with p == NULL } bool is_first_char_valid_alpha(const char *p) { return p != NULL && isalpha(p[0]); // 1) no unneeded isalpha() execution with p == NULL, 2) no SEGFAULT risk } Idiomatic conditional construct[edit]Since minimal evaluation is part of an operator's semantic definition and not an optional optimization, a number of coding idioms rely on it as a succinct conditional construct. Examples include: Perl idioms: some_condition or die; # Abort execution if some_condition is false some_condition and die; # Abort execution if some_condition is true POSIX shell idioms:[11] modprobe -q some_module && echo "some_module installed" || echo "some_module not installed" This idiom presumes that echo cannot fail. Possible problems[edit]Untested second condition leads to unperformed side effect[edit]Despite these benefits, minimal evaluation may cause problems for programmers who do not realize (or forget) it is happening. For example, in the code if (expressionA && myfunc(b)) { do_something(); } if myfunc(b) is supposed to perform some required operation regardless of whether do_something() is executed, such as allocating system resources, and expressionA evaluates as false, then myfunc(b) will not execute, which could cause problems. Some programming languages, such as Java, have two operators, one that employs minimal evaluation and one that does not, to avoid this problem. Problems with unperformed side effect statements can be easily solved with proper programming style, i.e., not using side effects in boolean statements, as using values with side effects in evaluations tends to generally make the code opaque and error-prone.[12] Reduced efficiency due to constraining optimizations[edit]Short-circuiting can lead to errors in branch prediction on modern central processing units (CPUs), and dramatically reduce performance. A notable example is highly optimized ray with axis aligned box intersection code in ray tracing.[clarification needed] Some compilers can detect such cases and emit faster code, but programming language semantics may constrain such optimizations.[citation needed] An example of a compiler unable to optimize for such a case is Java's Hotspot VM as of 2012.[13] See also[edit]
References[edit]
Which operators perform shortThe logical AND operator performs short-circuit evaluation: if the left-hand operand is false, the right-hand expression is not evaluated. The logical OR operator also performs short-circuit evaluation: if the left-hand operand is true, the right-hand expression is not evaluated.
Which logical operators perform shortWhich logical operators perform short-circuit evaluation? Short-circuit evaluation is performed with the not operator.
What is shortShort-circuit evaluation, minimal evaluation, or McCarthy evaluation (after John McCarthy) is the semantics of some Boolean operators in some programming languages in which the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression: when the first ...
What is meant by shortShort-Circuit Evaluation: Short-circuiting is a programming concept in which the compiler skips the execution or evaluation of some sub-expressions in a logical expression. The compiler stops evaluating the further sub-expressions as soon as the value of the expression is determined.
|