A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
The ternary operator condition ? value_if_true : value_if_false is an expression, not a statement. It evaluates to a value. You can assign it, pass it as an argument, embed it in a return statement. It is the only C operator that takes three operands. Used well, it replaces a four-line if-else with one readable line. Used badly, it nests into an unreadable pyramid that makes code reviewers reach for the delete key.
#include <stdio.h>int main(void) {int age = 20;const char *status = (age >= 18) ? "adult" : "minor";printf("Status: %s\n", status);int a = 15, b = 23;int max = (a > b) ? a : b;printf("Max: %d\n", max);int x = 0;printf("x is %s\n", x ? "nonzero" : "zero");return 0;}
The second and third operands must have compatible types or be convertible to a common type. Mixing int and double promotes the int to double. Mixing char* and int is a constraint violation in modern C. The result type is the common type after usual arithmetic conversions. If you need different types in the two branches, cast explicitly.
#include <stdio.h>int main(void) {int flag = 1;double result = flag ? 3.14 : 42;printf("Result: %.2f (type promoted to double)\n", result);return 0;}
Do not nest ternary operators. Do not use them for side effects. Do not use them when the branches are complex expressions. A ternary should be a simple value selection. If either branch is a function call with side effects, or if you need more than one line, use an if-else. The goal is readability, not brevity.
The ternary operator is a tool for simple value selection. Keep it flat. Keep it short. Keep it readable. The moment you are tempted to nest one inside another, stop and write an if-else. Next: relational operators, the comparison primitives that drive every conditional in the language.
Finish the lesson once you have worked through the material. This awards ★ 20 XP.