Learn C - C Conditional Operator

The conditional operator evaluates to one of two expressions, depending on whether a logical expression evaluates true or false.

Because three operands are involved this operator is also referred to as the ternary operator.

The general representation of an expression using the conditional operator looks like this:

condition ? expression1 : expression2

How the operator is arranged in relation to the operands.

The ? character follows the logical expression, condition.

On the right of ? are two operands, expression1 and expression2, that represent choices.

The value that results from the operation will be the value of expression1 if condition evaluates to true, or the value of expression2 if condition evaluates to false.


Note that only one, either expression1 or expression2, will be evaluated.

x = y > 7 ? 25 : 50;

This statement results in x being set to 25 if y is greater than 7, or to 50 otherwise.

This is a nice shorthand way of producing the same effect as this:

if(y > 7)
  x = 25;
  x = 50;

For example, you could write an expression that compared two salaries and obtained the greater of the two, like this:

your_salary > my_salary ? your_salary : my_salary


Here's how you can handle that:

    #include <stdio.h>
//w ww  .  j av a2s.  co m
    int main(void)
      const double PRICE = 3.50;                // Unit price in dollars
      const double rate1 = 0.05;            // Discount for more than 10
      double my_rate = 0.0;

      int quantity = 0;

      printf("Enter the number that you want to buy:");
      scanf(" %d", &quantity);

      my_rate = quantity > 10 ? rate1 : 0.6;

      printf("The price for %d is $%.2f\n", quantity, my_rate);
      return 0;

The code above generates the following result.