C # difference between & and &

Source: Internet
Author: User
I didn't pay much attention to the difference between the two (I don't even know "&"), because they are all "and" operators. I noticed this when I saw the third edition of C # High editor yesterday. I checked the msdn and posted the difference to remind myself from time to time.

Binary operators (&) pre-define Binary & operators for integer and bool types. For an integer, & calculates the bitwise "and" of the operands ". For bool operands, & calculate the logic of the operands "and"; that is, the result is true only when both operands are true. The condition "and" Operator (&) executes the logical "and" Operation of the Boolean operand, but only calculates the second operand if necessary. It is similar to the binary operator (&). The difference is that if X is false, Y is not calculated (because no matter what value Y is, the result of the operation is false ). This is called a "Short Circuit" calculation.

The following example illustrates the problem

// 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
(&) Can also be used as a unary operator to return the address of the operand.

PS.
(|) And (|) operators are the same.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.