C Ternary operator

Description

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

This operator is also referred to as the ternary operator.

Syntax

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

condition ? expression1 : expression2

Ternary operator vs if

You can use the conditional operator in a statement such as this:

x = y > 7 ? 25 : 50;

Executing this statement will result 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; 
else 
  x = 50; 

Use Ternary operator


#include <stdio.h>
/*from w w w  .ja va 2s.c om*/
int main(void)
{
  const double unit_price = 3.50;
  const double discount1 = 0.05; 
  const double discount2 = 0.1;  
  const double discount3 = 0.15;
  double total_price = 0.0;
  int quantity = 10;

  total_price = quantity > 50 ? discount3 : discount2;

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




















Home »
  C Language »
    Language Basics »




C Language Basics
Data Types
Operator
Statement
Array