C Conditional Operator

Beginner
6 min read
Updated: Nov 2026
1 example

What Is Conditional Operator?

The conditional (ternary) operator cond ? a : b evaluates cond; if it is true the result is a, otherwise b. It is an expression, so it can appear inside assignments and function arguments.

Remember
result = (condition) ? value_if_true : value_if_false;

int max = (a > b) ? a : b;
printf("%s\n", n % 2 == 0 ? "even" : "odd");

Cheat Sheet

Keep these facts handy while you work with Conditional Operator in C.

TopicDetail
OperandsThree: condition, true value, false value
AssociativityRight to left
TypesBoth branches convert to a common type
NestingAllowed but hurts readability

C Examples

Compile each example with gcc file.c -std=c11 -Wall -o out. Next: sizeof Operator.

Example 1 — Max and parity with ?:

Replace short if-else blocks with expressions.

C
#include <stdio.h>

int main(void) {
    int a = 12, b = 20;
    int max = (a > b) ? a : b;

    for (int n = 1; n <= 3; n++) {
        printf("%d is %s\n", n, n % 2 == 0 ? "even" : "odd");
    }
    printf("max = %d\n", max);
    return 0;
}

How It Works

  1. a > b is false, so max takes b.
  2. The ternary supplies the string argument to printf.
  3. Only the chosen branch is evaluated.

Edge Cases & Pitfalls

Check these before relying on Conditional Operator in real programs.

nest

Deep nesting

a ? b : c ? d : e is legal but hard to read. Use if-else for more than two outcomes.

type

Mismatched branch types

cond ? 1 : 2.5 yields a double either way. Keep both branches the same type.

Key Takeaways

  • Use: small two-way choices.
  • Value: it is an expression, not a statement.
  • Readability: avoid deep nesting.

One line: The conditional (ternary) operator cond ? a : b evaluates cond; if it is true the result is a, otherwise b.

Frequently Asked Questions

Usually no; the compiler generates similar code. Choose the one that reads better.
Yes, but a chain quickly becomes unreadable. Prefer else-if for three or more outcomes.
Continue with "C sizeof Operator" next. Find the size in bytes of a type or object at compile time. The C Operators hub lists every topic in order.

Next: sizeof Operator

Find the size in bytes of a type or object at compile time.

Continue →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

10 people found this page helpful