Hello everybody, my English not good, I wish many people can understand what I wrote :D You know "|" and "||" are meaning "or", "&" and "&&" are meaning "and" then what is difference ? Look at this code
int a = 0,b = 1;
if(b||a++);
cout<<a;
output: 0
int a = 0,b = 1;
if(b|a++);
cout<<a;
output: 1 I don't know why but I think || and && is smart, in this example when b==1 (true) then b "or" something is true, so "||" don't care after if sentese true in anyway. And "&&" is the same,
int a = 0,b = 1;
if(a && b++);
cout<<b;
int a = 0,b = 1;
if(a & b++);
cout<<b;
let try and see :). That is my second blog, My first blog is very bad, I wish this blog is better, sorry because my english is very bad. Thank for reading !
If one of operands in
||
equal totrue
then all istrue
. The same in&&
, if one equal tofalse
then all isfalse
. So not needed to calculate all operands if result is known in first step (b=1
in first example anda=0
in second).Personally, I think that no operator is smarter than other one. In comparison between "|" (binary or) and "||" (logic or), "|" must evaluate both operands to come up with correct result. On the other hand, "||" can skip the latter if the former is true.
In your code, C++ understand you and cast int b to bool when you use "||" or "&&".
x = 0 & y;
do you need value of y to compute x?
comment deleted
No. The truth is so, that there is C++ standart, which said:
No can or need, but must.
|| is a logical operator and yes it is "smart" so it don't check second parameter if first one is true. But | is a binary operator. It applies the logical or to each bit of numbers. like 5 | 6 = 7. Google it you will understand.