C #, the difference between & and &&

Note how did the previous difference between the two (I do not even know "&"), because they are "and" operator. I think yesterday the third edition compiled C # high when we come to notice this point, the next check MSDN, the difference stickers, and remind myself.

Binary operator (&) bool type integer and & predefined binary operator. For integer operands & computing the bitwise "and." For bool operands, & computes the logical operand "and"; that is, if and only if both operands are true, whose result is true. Conditions "and" operator (&&) Boolean logic to perform an operation "and" operation, but if necessary, only the calculation of the second operand. It like, except that the binary operator (&), if x is false, y is not calculated (because no matter what the value of y, are the result of the operation is false). This is known as a "short circuit" computing.

The following are examples of the most telling

//  cs_operator_logical_and.cs  
using System; 
class Test  

   static bool fn1()  
   
      Console.WriteLine("fn1 called"); 
      return false
   }
 
 
   static bool fn2()  
   
      Console.WriteLine("fn2 called"); 
      return true
   }
 
 
   public static void Main()  
   
      Console.WriteLine("regular AND:"); 
      Console.WriteLine("result is {0}", fn1() & fn2()); 
      Console.WriteLine("short-circuit AND:"); 
      Console.WriteLine("result is {0}", fn1() && fn2()); 
   }
 
}

Output:

regular AND: 
fn1 called 
fn2 called 
result is False 
short-circuit AND: 
fn1 called 
result is False

BTW 
(&) may also be used as a unary operator, returns the address of the operand

PS. 
(|) And (||) operator is the same reason

Reproduced in: https: //www.cnblogs.com/zhangchenliang/archive/2012/02/29/2373064.html

Guess you like

Origin blog.csdn.net/weixin_34258838/article/details/93495008