Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For multiple Booleans evaluation, is using && more efficient than ||?

Tags:

c++

Assume we want to evaluate the Boolean value of (A || B || C) which is logically equal to !(!A && !B && !C).

Would it be more time-efficient to use !(!A && !B && !C) than the other if (!A) is false since the whole expression value becomes false? Will the program notice that? Or the program still needs to evaluate the value of (!B) and (!C) before returning the final result?

P.S. Just correcting the de'Morgan expressions and change from ~ to !. Thanks guys.

P.S.2 shown in this link by Retired Ninja and optimized version by David Foerster. The assembly code is actually the same!

like image 475
ctanakul Avatar asked Apr 22 '18 02:04

ctanakul


People also ask

Can you use multiple Boolean operators?

You can have multiple Boolean Operators in one statement. It doesn't matter that there are multiple statements. Each statement must be true in order for the whole to evaluate to True .

What are the two values of booleans?

As we know, a variable of the type boolean can take on only two values: true and false.

How many conditions can Boolean have?

Named after George Boole (1815-1864), who invented mathematical logic and defined Boolean algebra. A variable of the primitive data type boolean can have two values: true and false (Boolean literals). or off. Boolean expressions use relational and logical operators.

What is Boolean test in Java?

A Boolean expression is a Java expression that returns a Boolean value: true or false .


1 Answers

(A || B || C) is logically equal to !(!A && !B && !C), you were missing the inner !s. The short circuiting in the second expression happens when !A is false, or equivalently when A is true. But when A is true, the first expression also short-circuits. In other words, these two expressions behave the same way with respect to short circuiting.

As Retired Ninja mentions in a comment, the two expressions produce the same assembly code, so there is no difference at all between them, except that one is harder to read.

like image 81
k_ssb Avatar answered Sep 23 '22 06:09

k_ssb