Saturday 7 January 2012

Conditional Operator

Conditional operator is sometimes called tenary operator or trinary operator because it is a shorthand of combination of the if-else and return statement and has three operands. 
The syntax of C ternary operator is as follows:
condition ? expression 1 : expression 2
C first evaluates the condition. Based on the return value of the condition the second or third operand is evaluated:
If the condition is evaluated to true (1), only the second operand (expresion 1) is evaluated. Then the operator return the value of the expression 1.
If the condtion is evaluated to false (0), only the third operand (expression 2) is evaluated. The value of the expression 2 is returned.
The ternary operator can be rewritten as the if-else and return statement as follows
if(condition)
   return expression1;
else
   return expression2;
Example of C Ternary Operator
In this example, we are going to write an inline function that uses C ternary operator to find the minimum number between two integers.
/*Purpose: A program demonstrates C ternary operator */
#include <stdio.h>
#include <stdlib.h>
/* Find min of two integers
   @param x
   @param y
   @return minimum value of x and y */
inline int min(int x, int y) { return x <= y ? x : y; }
int main(int argc, char** argv) 
{
    int x = 10;
    int y = 15;
    printf("x=%d,y=%d\n", x, y);
    printf("min(x,y)=%d\n", min(x, y));
    return (0);
}
x=10,y=15
min(x,y)=10

No comments:

Post a Comment

host gator coupon