conditional expressions

The purpose of the conditional expression is to select one of two expressions depending on a third, boolean, expression. The format for the conditional expression is
<boolean-expression> ? <expression-1> : <expression-2>
If the value of the <boolean-expression> is true, the value of the conditional expression is the value of <expression-1>; if it is false, the value of the conditional expression is the value of <expression-2>.
An important point is that only one of <expression-1> and <expression-2> is evaluated when evaluating the conditional expression. For example, the divide-by-zero in the following expression causes no error because it is not evaluated:
true ? 7 : 7/0
Expressions <expression-1> and <expression-2> may be any expressions, as long as they have the same type (if one is wider than the other, the narrower one will automatically be promoted to the wider type).
The conditional expression is known as a ternary operation, because it has three operands.

Examples of use

You can use a conditional expression anywhere you could use a more conventional expression. The following example uses the conditional expression to set c to the larger of a and b:
c= a > b ? a : b;
Be careful. The conditional operators ? and : have the lowest priority of all operators. It is helpful to use parenthesizes around the conditional expression in complicated situations.
Here's an example that creates a string that indicates which is the larger of a and b:
"The larger of a and b is " + (a > b ? "a: " + a : "b: " + b)
Try writing a few conditional expressions in the interactions pane in order to get familiar with them. For example, write an expression that finds the smallest of three values bc, and d.

Use the conditional expression with care

Used indiscriminately, the conditional expression can be hard to read. However, in some cases, its use can result in shorter and simpler code. For example, consider setting a variable s to the catenation of two strings: (1) either "Fahrenheit" or "Centigrade", depending on whether b is true or false, and (2) " hot" or " cold", depending whether is positive or not. We write:
s= (b ? "Fahrenheit" : "Centigrade")   +  (c > 0 ? " hot" : " cold");
In order to write this assignment without using the conditional expression, you would need a sequence of statements and would probably use at least two conditional statements if (...) ... else ....

Live Example : Check whether Number is Odd or Even

#include<stdio.h>

int main()
{
int num;

printf("Enter the Number : ");
scanf("%d",&num);

flag = ((num%2==0)?1:0);

if(flag==0)
   printf("\nEven");
else
   printf("\nOdd");
}
More Simply we can write this program as –
#include<stdio.h>

int main()
{
int num;

printf("Enter the Number : ");
scanf("%d",&num);

(num%2==0)?printf("Even"):printf("Odd");

}

No comments:

Post a Comment