Блог пользователя Son_Nguyen

Автор Son_Nguyen, 10 лет назад, По-английски

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 !

  • Проголосовать: нравится
  • +3
  • Проголосовать: не нравится

»
10 лет назад, # |
  Проголосовать: нравится +1 Проголосовать: не нравится

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 лет назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

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 лет назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

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