Is there any difference between && and & with bool(s)?
The standard guarantees that false
converts to zero and true
converts to one as integers:
4.7 Integral conversions
...
If the destination type is bool, see 4.12. If the source type is bool, the value false is converted to zero and the value true is converted to one.
So the effect in the example you give is guaranteed to be the same and is 100% portable.
For the case you give, any decent compiler is likely to generate identical (optimal) code.
However, for Boolean expressions expr1
and expr2
, it is not true in general that expr1 && expr2
is the same as expr1 & expr2
because &&
performs "short-circuit" evaluation. That is, if expr1
evaluates to false
, expr2
will not even be evaluated. This can affect performance (if expr2
is complicated) and behavior (if expr2
has side-effects). (But note that the &
form can actually be faster if it avoids a conditional branch... Toying with this sort of thing for performance reasons is almost always a bad idea.)
So, for the specific example you give, where you load the values into local variables and then operate on them, the behavior is identical and the performance is very likely to be.
In my opinion, unless you are specifically relying on the "short-circuit" behavior, you should choose the formulation that most clearly expresses your intention. So use &&
for logical AND and &
for bit-twiddling AND, and any experienced C++ programmer will find your code easy to follow.
Differences in boolean operators: & vs && and | vs ||
Those are the bitwise AND and bitwise OR operators.
int a = 6; // 110
int b = 4; // 100
// Bitwise AND
int c = a & b;
// 110
// & 100
// -----
// 100
// Bitwise OR
int d = a | b;
// 110
// | 100
// -----
// 110
System.out.println(c); // 4
System.out.println(d); // 6
Thanks to Carlos for pointing out the appropriate section in the Java Language Spec (15.22.1, 15.22.2) regarding the different behaviors of the operator based on its inputs.
Indeed when both inputs are boolean, the operators are considered the Boolean Logical Operators and behave similar to the Conditional-And (&&
) and Conditional-Or (||
) operators except for the fact that they don't short-circuit so while the following is safe:
if((a != null) && (a.something == 3)){
}
This is not:
if((a != null) & (a.something == 3)){
}
"Short-circuiting" means the operator does not necessarily examine all conditions. In the above examples, &&
will examine the second condition only when a
is not null
(otherwise the whole statement will return false, and it would be moot to examine following conditions anyway), so the statement of a.something
will not raise an exception, or is considered "safe."
The &
operator always examines every condition in the clause, so in the examples above, a.something
may be evaluated when a
is in fact a null
value, raising an exception.
Boolean operators && and ||
The shorter ones are vectorized, meaning they can return a vector, like this:
((-2:2) >= 0) & ((-2:2) <= 0)
# [1] FALSE FALSE TRUE FALSE FALSE
The longer form evaluates left to right examining only the first element of each vector, so the above gives
((-2:2) >= 0) && ((-2:2) <= 0)
# [1] FALSE
As the help page says, this makes the longer form "appropriate for programming control-flow and [is] typically preferred in if clauses."
So you want to use the long forms only when you are certain the vectors are length one.
You should be absolutely certain your vectors are only length 1, such as in cases where they are functions that return only length 1 booleans. You want to use the short forms if the vectors are length possibly >1. So if you're not absolutely sure, you should either check first, or use the short form and then use all
and any
to reduce it to length one for use in control flow statements, like if
.
The functions all
and any
are often used on the result of a vectorized comparison to see if all or any of the comparisons are true, respectively. The results from these functions are sure to be length 1 so they are appropriate for use in if clauses, while the results from the vectorized comparison are not. (Though those results would be appropriate for use in ifelse
.
One final difference: the &&
and ||
only evaluate as many terms as they need to (which seems to be what is meant by short-circuiting). For example, here's a comparison using an undefined value a
; if it didn't short-circuit, as &
and |
don't, it would give an error.
a
# Error: object 'a' not found
TRUE || a
# [1] TRUE
FALSE && a
# [1] FALSE
TRUE | a
# Error: object 'a' not found
FALSE & a
# Error: object 'a' not found
Finally, see section 8.2.17 in The R Inferno, titled "and and andand".
Usage of '&' versus '&&'
&
is a bitwise AND, meaning that it works at the bit level. &&
is a logical AND, meaning that it works at the boolean (true/false) level. Logical AND uses short-circuiting (if the first part is false, there's no use checking the second part) to prevent running excess code, whereas bitwise AND needs to operate on every bit to determine the result.
You should use logical AND (&&
) because that's what you want, whereas &
could potentially do the wrong thing. However, you would need to run the second method separately if you wanted to evaluate its side effects:
var check = CheckSomething();
bool IsValid = isValid && check;
What is the difference between & and && in Java?
& <-- verifies both operands
&& <-- stops evaluating if the first operand evaluates to false since the result will be false
(x != 0) & (1/x > 1)
<-- this means evaluate (x != 0)
then evaluate (1/x > 1)
then do the &. the problem is that for x=0 this will throw an exception.
(x != 0) && (1/x > 1)
<-- this means evaluate (x != 0)
and only if this is true then evaluate (1/x > 1)
so if you have x=0 then this is perfectly safe and won't throw any exception if (x != 0) evaluates to false the whole thing directly evaluates to false without evaluating the (1/x > 1)
.
EDIT:
exprA | exprB
<-- this means evaluate exprA
then evaluate exprB
then do the |
.
exprA || exprB
<-- this means evaluate exprA
and only if this is false
then evaluate exprB
and do the ||
.
Why do we usually use || over |? What is the difference?
If you use the ||
and &&
forms, rather than the |
and &
forms of these operators, Java will not bother to evaluate the right-hand operand alone.
It's a matter of if you want to short-circuit the evaluation or not -- most of the time you want to.
A good way to illustrate the benefits of short-circuiting would be to consider the following example.
Boolean b = true;
if(b || foo.timeConsumingCall())
{
//we entered without calling timeConsumingCall()
}
Another benefit, as Jeremy and Peter mentioned, for short-circuiting is the null reference check:
if(string != null && string.isEmpty())
{
//we check for string being null before calling isEmpty()
}
more info
Difference between & and && in Java?
&
is bitwise.&&
is logical.
&
evaluates both sides of the operation.&&
evaluates the left side of the operation, if it's true
, it continues and evaluates the right side.
Related Topics
How to Determine the Amount of Linux System Ram in C++
Openmp: What Is the Benefit of Nesting Parallelizations
Difference Between A* Pa = New A; and A* Pa = New A();
Std::Back_Inserter for a Std::Set
Why Must Std::Sort Compare Function Return False When Arguments Are Equal
Why Can't Std::Ostream Be Moved
Which Is Faster: X<<1 or X<<10
C++ [Windows] Path to the Folder Where the Executable Is Located
Can the 'Type' of a Lambda Expression Be Expressed
Std::Unique_Ptr with Derived Class
Simpler Way to Create a C++ Memorystream from (Char*, Size_T), Without Copying the Data
Do Pthread Mutexes Work Across Threads If in Shared Memory
Erase/Remove Contents from the Map (Or Any Other Stl Container) While Iterating It
Some Clarification Needed About Synchronous Versus Asynchronous Asio Operations
Does Try-Catch Block Decrease Performance
Determining the Alignment of C/C++ Structures in Relation to Its Members