egsoftweb@gmail.com
 facebook.com/egsoftweb

The ternary ( ? ) Operator

 c tutorials |  Admin

It is called ternary operator because it requires three operands.

Syntax:

           Exp1 ? Exp2 : Exp3   

 

and equivalent to

 

     if (Exp1)

            Exp2;

     else

            Exp3;

 

Here Exp1 is evaluated & If it is true, Exp2 is evaluated and becomes the value of the entire ? expression. If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the entire ? expression.

 

Examples:

//sign function

int sign(int x)

{

      int result;

      result = x ? (x > 0 ? 1 : -1) : 0;

      return result;

}

 

//or also we can do it simply by

int sign(int x)

{

      return x ? (x > 0 ? 1 : -1) : 0;

}

// factorial function

#include <stdio.h>

int fact(int x)

{

      return x ? x*fact(x - 1) : 1;

}

 

int main()

{

      int i = 0;

      printf("Factorial of %d is %d\n", i, fact(i));

      i++;

      printf("Factorial of %d is %d\n", i, fact(i));

      i++;

      printf("Factorial of %d is %d\n", i, fact(i));

      i++;

      printf("Factorial of %d is %d\n", i, fact(i));

      i++;

      printf("Factorial of %d is %d\n", i, fact(i));

      i++;

      printf("Factorial of %d is %d\n", i, fact(i));

      i++;

      printf("Factorial of %d is %d\n", i, fact(i));

      i++;

      printf("Factorial of %d is %d\n", i, fact(i));

      i++;

      printf("Factorial of %d is %d\n", i, fact(i));

      i++;

      printf("Factorial of %d is %d\n", i, fact(i));

      i++;

      printf("Factorial of %d is %d\n", i, fact(i));

      getchar();

      return 0;

}