Checking multiple IF conditions in single statement.

if (addMore)
{
y = x + moreValue;
}
else
{
y = x;
}
can be compressed into:

y = (addMore ? x + moreValue : x);

How can this be compressed into one statement.

if (addMore) {
    y = x + moreValue;
} else if (50 < x) {
    y = 50;
} else {
    y = x;
}

Ans:

Using Ternary operator, more than one condition can check.
if First condition is true then compare with second value.

y = 
  addMore ? x + moreValue :
  50 < x  ? 50            :
            x;

OR


y = (addMore ? x + moreValue : (50 < x ? 50 : x));
 
Advertisements

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