🎓 A1Learner
🔍
0 of 50 lessons completed

C Ternary Operator

A ternary operator chooses between two values from a check. Comparisons gave true-or-false answers; the ternary turns that answer into a value in one line.

Pick a price

Age is 10, so the check is true and the small price is picked. The print line shows 5.

#include <stdio.h>

int main() {
  int age = 10;
  int price = (age < 18) ? 5 : 10;
  printf("%d\n", price);
  return 0;
}

Pick the other value

Score is 40, so the check is false and the second value is picked. The print line shows 0.

#include <stdio.h>

int main() {
  int score = 40;
  int points = (score > 50) ? 100 : 0;
  printf("%d\n", points);
  return 0;
}

Two checks at once

Age is 25 and hasCard is true, so both parts of the joined check are true. The first value is picked, and the print line shows 1.

#include <stdio.h>
#include <stdbool.h>

int main() {
  int age = 25;
  bool hasCard = true;
  int entry = (age > 17 && hasCard) ? 1 : 0;
  printf("%d\n", entry);
  return 0;
}

Example

#include <stdio.h>

int main() {
  int age = 65;
  int ticket = (age > 60) ? 5 : 12;
  printf("%d\n", ticket);
  return 0;
}

Key points

  • The ternary operator uses a question mark and a colon: check ? first : second.
  • The check comes before the question mark.
  • The value before the colon is picked when the check is true.
  • The value after the colon is picked when the check is false.
  • A ternary line fits a small choice in one line.
  • The two values should be the same type.
  • Use an if statement for a bigger choice, and a ternary for a small one.

Age is 65, so the check age > 60 is true and ticket takes 5. As an if statement it would read: if age is larger than 60, ticket is 5; otherwise ticket is 12.

Note

A ternary picks a value. It does not run a block of code.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does (age < 18) ? 5 : 10 give when age is 20?