+ 1

What is the diffrent between (&&) and (&) inside a code ?

If you delete it , it won't affect the code ..

21st Dec 2017, 3:30 AM
Mohammed Mahil
Mohammed Mahil - avatar
3 Antworten
+ 6
& <-- 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 ||.
21st Dec 2017, 3:43 AM
James16
James16 - avatar
+ 5
There is a difference (well, two), though you wouldn't see it in your example. "&" does a bitwise "AND" operation, meaning that 0x1 & 0x1 = 0x1, but 0x1 & 0x2 = 0x0. OTOH, "&&" is a boolean/logical "AND", meaning it treats any non-zero value as a TRUE, so 0x1 && 0x1 = TRUE (which is generally represented as -1, ie, all ones [or maybe it's represented as 1 in C++, I forget]), while 0x1 && 0x2 = TRUE as well. In addition, "&&" is short-circuiting, meaning that if the first operand is FALSE, the second won't be evaluated. So, while FALSE & null_pointer->booleanField ==> null pointer exception, FALSE && null_pointer->booleanField = FALSE. There may be a slight performance advantage in using bitwise operations in some cases, but generally you should use the double forms when evaluating boolean values, so that your code is independent of the precise representation of boolean TRUE and FALSE.
21st Dec 2017, 3:43 AM
GAWEN STEASY
GAWEN STEASY - avatar
0
thank you #james16 and #gawen_steast alot .
21st Dec 2017, 4:13 AM
Mohammed Mahil
Mohammed Mahil - avatar