Wednesday

C Ternary Operator



C Ternary Operator

Introduction to C Ternary Operator

C ternary operator is also referred as conditional operator or trinary operator because:
  • It is only operator that has three operands.
  • It is a shorthand of combination of the if-else and return statement.
The syntax of C ternary operator is as follows: 
1condition ? 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:
1if(condition)
2   return expression1;
3else
4   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.


#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






In this tutorial, you've learned about C ternary operator to make your code shorter and easier to read.








Kindly Bookmark this Post using your favorite Bookmarking service:
Technorati Digg This Stumble Stumble Facebook Twitter
YOUR ADSENSE CODE GOES HERE

0 comments:

Post a Comment

Dont Forget for Commets

 

| C programing tutorials © 2009. All Rights Reserved | Template Style by My Blogger Tricks .com | Design by Brian Gardner | Back To Top |