#92 – The Ternary Conditional Operator

The conditional operator (?:) take three operands.  The first is a boolean expression to evaluate. If this expression is true, the value of the conditional operator is equal to the second operand.  If it’s false, the value of the conditional operator is equal to the third operand.

So for the expression

 a ? b : c

the value of this expression is b if a is true, or c if a is false.

Here’s an example of using the conditional operator (assume that isRaining is a boolean):

string describeWeather = isRaining ? "Wet" : "Nice";

A conditional operator can always be rewritten as an if statement.  The previous example is equivalent to:

string describeWeather;
if (isRaining)
    describeWeather = "Wet";
else
    describeWeather = "Nice";

Using the conditional operator can lead to more concise code.

Advertisements

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

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: