Menu
Coddy logo textTech

Ternary Conditional Operator

Part of the Fundamentals section of Coddy's C journey — lesson 29 of 63.

The ternary conditional operator is a shorthand way to express an if-else statement in a single line.

The syntax is:

condition ? value_if_true : value_if_false;

Let's look at an example. First, here's a traditional if-else statement:

int max;
if (a > b) {
    max = a;
} else {
    max = b;
}

Now, let's rewrite it using the ternary operator:

int max = (a > b) ? a : b;

In this example:

  • a > b is the condition
  • If the condition is true, a is returned
  • If the condition is false, b is returned

The ternary operator can also be nested, but this can make code harder to read:

int x = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);
challenge icon

Challenge

Easy

Create a program that checks if a number is positive, negative, or zero using the conditional operator. The program should:

  1. Take an integer input from the user.
  2. Use the conditional operator to determine if the number is positive, negative, or zero.
  3. Print the result in the format: "The number is [positive/negative/zero]".

Cheat sheet

The ternary conditional operator provides a shorthand way to express an if-else statement in a single line.

Syntax:

condition ? value_if_true : value_if_false;

Example comparing traditional if-else with ternary operator:

// Traditional if-else
int max;
if (a > b) {
    max = a;
} else {
    max = b;
}

// Ternary operator
int max = (a > b) ? a : b;

The ternary operator can be nested, though this reduces readability:

int x = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);

Try it yourself

#include <stdio.h>

int main() {
    int number;
    scanf("%d", &number);
    
    // Write your code below
    char* result = 
    
    printf("The number is %s\n", result);
    return 0;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals