Home C ternary operator in C tutorial

ternary operator in C tutorial

The ternary operator in C is a shorthand for the if-else statement and is often used for concise conditional expressions. It’s also known as the conditional operator.

This operator is useful for simple conditions where you need to assign a value or perform a quick check without writing a full if-else block.

Syntax of the Ternary Operator

condition ? expression_if_true : expression_if_false;
  • If the condition is true, expression_if_true is executed.
  • If the condition is false, expression_if_false is executed.

1. Basic Example of the Ternary Operator

The following example demonstrates the basic usage of the ternary operator to check if a number is positive, negative, or zero.

#include <stdio.h>

int main() {
    int num = 10;
    int result = (num > 0) ? 1 : 0;

    printf("Is the number positive? %d\n", result);

    return 0;
}

Explanation:

  • num > 0 is the condition.
  • If num > 0 is true, result is set to 1.
  • If num > 0 is false, result is set to 0.

Output:

Is the number positive? 1

2. Using the Ternary Operator for Simple Assignment

The ternary operator can be used to assign a variable based on a condition. Here’s an example where we determine the maximum of two numbers.

#include <stdio.h>

int main() {
    int a = 5;
    int b = 10;

    int max = (a > b) ? a : b;
    printf("The maximum value is: %d\n", max);

    return 0;
}

Explanation:

  • (a > b) ? a : b checks if a is greater than b.
  • If true, max is assigned the value of a.
  • Otherwise, max is assigned the value of b.

Output:

The maximum value is: 10

3. Using the Ternary Operator in printf Statements

You can use the ternary operator directly within printf statements to print different messages based on a condition.

#include <stdio.h>

int main() {
    int age = 18;

    printf("You are %s\n", (age >= 18) ? "an adult" : "not an adult");

    return 0;
}

Explanation:

  • (age >= 18) ? “an adult” : “not an adult” checks if age is 18 or more.
  • If true, “an adult” is printed.
  • If false, “not an adult” is printed.

Output:

You are an adult

4. Nesting the Ternary Operator

You can nest ternary operators to perform multiple checks. This can sometimes reduce the need for else if statements.

Example: Checking if a Number is Positive, Negative, or Zero

#include <stdio.h>

int main() {
    int num = -3;

    const char* result = (num > 0) ? "Positive" : (num < 0) ? "Negative" : "Zero";
    printf("The number is %s\n", result);

    return 0;
}

Explanation:

  • (num > 0) ? “Positive” : (num < 0) ? “Negative” : “Zero” first checks if num is greater than 0.
  • If true, it returns “Positive”.
  • If false, it checks if num < 0. If true, it returns “Negative”.
  • If both conditions are false, it returns “Zero”.

Output:

The number is Negative

5. Using the Ternary Operator with Function Calls

You can use the ternary operator to decide which function to call based on a condition. This can be useful for quick conditional function calls.

Example: Choosing Between Two Functions

#include <stdio.h>

void printEven() {
    printf("The number is even.\n");
}

void printOdd() {
    printf("The number is odd.\n");
}

int main() {
    int num = 7;

    (num % 2 == 0) ? printEven() : printOdd();

    return 0;
}

Explanation:

  • (num % 2 == 0) ? printEven() : printOdd() checks if num is even.
  • If true, printEven() is called.
  • If false, printOdd() is called.

Output:

The number is odd.

6. Using the Ternary Operator in Array Indexing

The ternary operator can be helpful for conditional array indexing, where you might want to choose between different indices based on a condition.

Example: Conditional Array Indexing

#include <stdio.h>

int main() {
    int arr[2] = {100, 200};
    int flag = 1;

    int value = arr[(flag == 1) ? 1 : 0];
    printf("Selected value: %d\n", value);

    return 0;
}

Explanation:

  • (flag == 1) ? 1 : 0 evaluates the index to 1 if flag is 1, otherwise to 0.
  • This is useful when choosing between two values in an array based on a condition.

Output:

Selected value: 200

7. Multiple Conditions with the Ternary Operator

You can combine multiple conditions in a single ternary expression using logical operators.

Example: Checking Multiple Conditions

#include <stdio.h>

int main() {
    int age = 30;
    int income = 40000;

    const char* eligibility = (age > 18 && income > 30000) ? "Eligible" : "Not Eligible";
    printf("Loan Eligibility: %s\n", eligibility);

    return 0;
}

Explanation:

  • (age > 18 && income > 30000) ? “Eligible” : “Not Eligible” checks if both conditions are true.
  • If true, “Eligible” is printed; otherwise, “Not Eligible” is printed.

Output:

Loan Eligibility: Eligible

8. Using the Ternary Operator to Avoid Division by Zero

The ternary operator can help avoid potential errors, like division by zero, by choosing an alternative value.

Example: Preventing Division by Zero

#include <stdio.h>

int main() {
    int numerator = 10;
    int denominator = 0;

    int result = (denominator != 0) ? (numerator / denominator) : 0;
    printf("Result: %d\n", result);

    return 0;
}

Explanation:

  • (denominator != 0) ? (numerator / denominator) : 0 checks if denominator is non-zero.
  • If true, numerator / denominator is computed.
  • If false, 0 is assigned to result to prevent division by zero.

Output:

Result: 0

9. Returning Values from Functions with Ternary Operator

The ternary operator can be used directly in return statements to make functions more concise.

Example: Returning Different Values Based on Condition

#include <stdio.h>

const char* checkSign(int num) {
    return (num > 0) ? "Positive" : (num < 0) ? "Negative" : "Zero";
}

int main() {
    int num = -5;
    printf("The number is %s\n", checkSign(num));

    return 0;
}

Explanation:

  • checkSign uses the ternary operator to return a string based on whether num is positive, negative, or zero.

Output:

The number is Negative

Summary Table of Ternary Operator Usage

Example Usage Scenario Code Example
Simple Condition Assigns value based on condition (a > b) ? a : b
In printf Statement Prints based on condition printf(“%s”, (flag) ? “True” : “False”);
Nested Condition Multiple checks in one line (a > 0) ? “Pos” : (a < 0) ? “Neg” : “Zero”
Function Call Calls different functions (a % 2 == 0) ? even() : odd();
Array Indexing Chooses array index based on condition arr[(flag) ? 1 : 0]
Avoid Division by Zero Prevents division error (den != 0) ? (num / den) : 0
Return Value from Function Direct return with condition return (a > 0) ? “Pos” : “Neg”;

Complete Example: Multiple Uses of the Ternary Operator

This example demonstrates various uses of the ternary operator within a single program.

#include <stdio.h>

const char* checkEligibility(int age, int income) {
    return (age >= 18 && income >= 30000) ? "Eligible" : "Not

 Eligible";
}

int main() {
    int age = 20;
    int income = 35000;
    int number = -10;

    printf("Age Eligibility: %s\n", (age >= 18) ? "Adult" : "Minor");
    printf("Loan Eligibility: %s\n", checkEligibility(age, income));
    printf("Number sign: %s\n", (number > 0) ? "Positive" : (number < 0) ? "Negative" : "Zero");

    return 0;
}

In this program:

  • The checkEligibility function uses the ternary operator for concise conditional checks.
  • The printf statements use nested ternary operators for conditional outputs.

Output:

Age Eligibility: Adult
Loan Eligibility: Eligible
Number sign: Negative

The ternary operator is a powerful tool in C programming for writing concise, readable code in conditions, especially when a quick decision is needed.

You may also like