Thursday, 5 March 2015

Conditional Operator in C

Conditional operator (?:) is one of the special operators supported by the C language. The conditional operator evaluates an expression and returns one of two values based on whether condition is TRUE or FALSE. 

It has the form:
condition ? result-1 : result-2;

If the condition is TRUE the expression returns result-1 and if not it returns result-2. Example 4.5 – Consider the following example which determines the value of variable “b” based on the whether the given input is greater than 50 or not.

/* Program-4.7 */
#include <stdio.h>
int main()
{
float u,v,t,a;
printf("Enter u (m/s): ");
scanf("%f", &u); //get starting velocity
printf("Enter v (m/s): ");
scanf("%f", &v); //get current velocity
printf("Enter t (s) : ");
scanf("%f", &t); //get time
if(t >= 0)
{
a = (v-u)/t;
printf("acceleration is: %.2f m/s", a);
}
else
printf ("Incorrect time");
return 0;
}
/* Program-4.8 */
#include <stdio.h>
int main()
{
int a,b;
printf("Enter value of a: ");
scanf("%d", &a); //get starting velocity
b = a > 50 ? 1 : 2;
printf("Value of b: %d", b);
return 0;
}
Executing Program-4.8 display the following:
Enter value of a: 51
Value of b: 1
Enter value of a: 45
Value of b: 2

If the input is greater than 50 variable “b” will be assigned “1” and if not it will be assigned “2”. Conditional operator can be used to implement simple if-else constructs. However use of conditional operator is not recommended in modern day programming since it may reduce the readability of the source code.

No comments:

Post a Comment