Son_Nguyen's blog

By Son_Nguyen, 10 years ago, In English

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 !

  • Vote: I like it
  • +3
  • Vote: I do not like it

»
10 years ago, # |
  Vote: I like it +1 Vote: I do not like it

If one of operands in || equal to true then all is true. The same in &&, if one equal to false then all is false. So not needed to calculate all operands if result is known in first step (b=1 in first example and a=0 in second).

»
10 years ago, # |
  Vote: I like it 0 Vote: I do not like it

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 "&&".

  • »
    »
    10 years ago, # ^ |
      Vote: I like it +9 Vote: I do not like it

    x = 0 & y;
    do you need value of y to compute x?

    • »
      »
      »
      10 years ago, # ^ |
      Rev. 4   Vote: I like it 0 Vote: I do not like it

      comment deleted

    • »
      »
      »
      10 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      No. The truth is so, that there is C++ standart, which said:

      • Binary operators must evaluate both operands
      • Logical operators must skip second operand if the first is enough

      No can or need, but must.

»
10 years ago, # |
  Vote: I like it 0 Vote: I do not like it

|| 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.