The ternary operator in C

The conditional operator can be used to test data. Since there are three operands involved, the conditional operator is also referred to as the ternary operator. In fact, the conditional operator is the the C language’s only ternary operator. It enables us to express conditional tests economically.


#include <stdio.h>
#include <string.h>

int main(void){
  int a, b;
  char string[50];
  a = 7;
  b = 2;
  (a > b) ? (strcpy(string, "var a is greater")) :
         (strcpy(string, "var b is greater"));
  printf("\n%s\n", string);

  printf("\nvar %c is greater\n",
     (a > b) ? 'a' : 'b');
  return 0;

Although parentheses are not required around the condition tested at the start of the ternary expression, they do help to improve readability.

It is possible to nest ternary operators one within another.

#include <stdio.h>

int main(void){
  const double price=4.99;
  const double discountA=.05;
  const double discountB=.10;
  const double discountC=.15;
  int quantity;
  int total = 0;
  double discount = 0.0;
    printf("Please enter the number of items that you will buy:\n");
    printf("Or enter a negative number to finish shopping.\n");
    scanf(" %d", &quantity);
      printf("Total = %d units.\n", total);
    } else {
   printf("You have ordered a total of %d units.\n", total);
    discount = (total>30 ? discountC : (
        (total>20 ? discountB : (
          (total>10 ? discountA : 0.0)))));
     * escape percent sign with two percent signs in a row
    printf("You qualify for a %d%% discount\n",
    printf("Your total comes to %.2f\n", total*price*(1.00-discount));
  return 0;