#91 – Conditional Operators Can Short-Circuit Evaluation

C# won’t necessarily evaluate every sub-expression in a larger expression.  If knowing the value of the first operand is sufficient for knowing the value of the entire expression, the larger expression is said to be short-circuited.

When evaluating a logical AND (&&), the second operand will not be evaluated if the first operand is false.  The entire expression is false.

bool b1 = false && expr;   // Result is false; expr never evaluated

When evaluating a logical OR (||), the second operand will not be evaluated if the first operand is true.  The entire expression is true.

bool b1 = true || expr;   // Result is true; expr never evaluated

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #91 – Conditional Operators Can Short-Circuit Evaluation

  1. Pingback: #985 – Why It’s Useful for Conditional Operators to Short-Circuit Evaluation | 2,000 Things You Should Know About C#

  2. kai zhou says:

    “short-circuited”.
    Thank you Sean.

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

%d bloggers like this: