We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Ternary

Like JavaScript, C has a ternary operator:

int a = 5;
int b = 10;
int max = a > b ? a : b;
printf("max: %d\n", max);
// max: 10

Let's break down the syntax:

a > b ? a : b
  • a > b is the condition
  • ? begins the "then" value
  • a is the final value if the condition is true
  • : separates the "else" value
  • b is the final value if the condition is false
  • The entire expression (a > b ? a : b) evaluates to either a or b, which is then assigned to max in our example.

Ternaries are a way to write a simple if/else statement in one line.

My recommendation? Don't use 'em. Okay just kidding, they're fine. Just don't use them like a JS Andy on every single line to just save 3 keystrokes. I find them most useful when you are trying to set a single value to the result of some boolean expression, like max in the example above. Generally speaking, I think you're better served with if statements in C.