&, | , &&, || what…?

A friend of mine was wondering the advantage over the various operators.  I used the wording short circuits and thus does not eval the portion of the op to the right.

I sent her to this documentation site

&& and || Operators

  • To avoid exceptions and increase performance by skipping unnecessary comparisons, use && instead of & and || instead of | when you perform comparisons, as shown in the following example.
                Console.Write("Enter a dividend: ");
                var dividend = Convert.ToInt32(Console.ReadLine());
    
                Console.Write("Enter a divisor: ");
                var divisor = Convert.ToInt32(Console.ReadLine());
    
                // If the divisor is 0, the second clause in the following condition
                // causes a run-time error. The && operator short circuits when the
                // first expression is false. That is, it does not evaluate the
                // second expression. The & operator evaluates both, and causes 
                // a run-time error when divisor is 0.
                if ((divisor != 0) && (dividend / divisor > 0))
                {
                    Console.WriteLine("Quotient: {0}", dividend / divisor);
                }
                else
                {
                    Console.WriteLine("Attempted division by 0 ends up here.");
                }
    

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s