C Ternary Operator (? : ) – A Shorter Way to Write if...else

The ternary operator in C is a compact, one-line version of an if...else statement. It helps you write cleaner and more concise code when dealing with conditional assignments or outputs.

Syntax of the Ternary Operator

condition ? expression_if_true : expression_if_false;

Meaning:

  • If the condition is true, execute expression_if_true.

  • If the condition is false, execute expression_if_false.

Simple Example

#include <stdio.h>

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

    printf("The maximum is %d\n", max);
    return 0;
}

Output:

The maximum is 20

Another Example – Pass/Fail

#include <stdio.h>

int main() {
    int marks = 75;
    char *result = (marks >= 50) ? "Pass" : "Fail";

    printf("Result: %s\n", result);
    return 0;
}

Output:

Result: Pass

Nesting Ternary Operators

#include <stdio.h>

int main() {
    int x = 0;
    char *result = (x > 0) ? "Positive" : (x < 0) ? "Negative" : "Zero";

    printf("x is %s\n", result);
    return 0;
}

Output:

x is Zero

When to Use the Ternary Operator

✅ Use Case📝 Example
Assign value conditionallyint min = (a < b) ? a : b;
Print messagesprintf("%s", (age >= 18) ? "Adult" : "Minor");
Return values in functionsreturn (x > y) ? x : y;

Best Practices

DoDon’t
Use it for simple logicAvoid complex nested conditions
Use parentheses for clarityDon’t overuse it in long expressions
Keep it readableDon’t replace all if...else with it

Common Mistakes

MistakeProblem
Using it for actions instead of valuesTernary is an expression, not a statement
Forgetting :Leads to compiler errors
Nesting without parenthesesMakes code unreadable and error-prone

Read More

How to Create Database in MySQL

  • By admin
  • November 27, 2021
  • 65 views
How to Create Database in MySQL

How to create table in MySQL

  • By admin
  • November 6, 2021
  • 46 views
How to create table in MySQL

MySQL commands with examples

  • By admin
  • September 11, 2021
  • 139 views
MySQL commands with examples

MySQL use database

  • By admin
  • May 28, 2021
  • 45 views
MySQL use database

System Software

  • By admin
  • May 20, 2021
  • 66 views

Introduction to software

  • By admin
  • May 13, 2021
  • 58 views
Introduction to software