1. Home
c tutorial

Explore C Tutorials: From Beginner Concepts to Advanced Techniques

Dive into our C tutorials and expand your programming skills. From fundamental concepts to advanced techniques, we've got you covered. Start your journey to C mastery today

  • 130 Lessons
  • 22 Hours
right-top-arrow

Tutorial Playlist

132 Lessons
120

C Ternary Operator

Updated on 20/05/20242,486 Views

In the world of programming, operators are essential tools that perform specific operations on one or more operands. Among various operators in C, the Ternary operator is an intriguing and efficient one. This article aims to provide a detailed understanding of the Ternary Operator in C, its working examples, comparison with if...else statements, and a few practice problems.

What is a Ternary Operator in C?

A Ternary Operator in C is a conditional operator that takes three arguments, hence the term 'ternary.' It provides a shorter way to code if-else statements and is extensively used to assign conditional values to variables. It is unique as it's the only operator in C that takes three operands.

Syntax

The general syntax of the Ternary Operator in C is as follows:

condition ? value_if_true : value_if_false;

Here, the operator first evaluates the 'condition.' If the 'condition' is true (non-zero), it returns 'value_if_true.' If the 'condition' is false (zero), it returns 'value_if_false.'

Working of Conditional/Ternary Operator in C

To understand the working of the ternary operator, let's use an example.

#include <stdio.h>

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

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

    printf("Maximum value is: %d", max);
   
    return 0;
}

In this example, we use the ternary operator to find the maximum between two numbers, 'a' and 'b'. The output is "Maximum value is: 20" as 'b' is greater than 'a'.

Flow Chart for Ternary Operator in C

Here is a simple flow diagram illustrating the ternary operator's working:

 Start
   |
Evaluate Condition
   |
   |__ Yes (Condition is true) --> Return Value_if_True --> End
   |
   |__ No  (Condition is false) --> Return Value_if_False --> End

This flowchart visualises the process the Ternary Operator in C undergoes while evaluating the condition and deciding the outcome based on the condition's truth value.

Examples

The Ternary Operator in C can be applied in a multitude of ways. Let's delve into some examples with various twists to highlight its versatility.

Example 1: Basic Example

This Ternary Operator in C example showcases the simplicity and straightforwardness of the ternary operator in a basic comparison operation:

#include <stdio.h>

int main() {
    int a = 5, b = 10;
    int max = (a > b) ? a : b;
    printf("The maximum value is %d", max);

    return 0;
}

In this code, 'max' will have the value of 'b' because 'a' is not greater than 'b'. Therefore, the condition is false.

Example 2: Nested Ternary Operator

The ternary operator can be nested. However, this can lead to code that is complicated to read:

#include <stdio.h>

int main() {
    int a = 5, b = 10, c = 15;
    int max = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);
    printf("The maximum value is %d", max);

    return 0;
}

This example finds the maximum of three numbers using nested ternary operators.

Example 3: Using Ternary Operator in Function Arguments

The ternary operator can be used directly in function arguments to make your code more compact:

#include <stdio.h>

void printMessage(int isEven) {
    printf(isEven ? "Number is even\n" : "Number is odd\n");
}

int main() {
    int num = 7;
    printMessage(num % 2 == 0);

    return 0;
}

In this example, the ternary operator is used to select the message to be printed based on the 'isEven' parameter.

Example 4: Using Ternary Operator for Variable Assignment

The ternary operator can be used for efficient variable assignment:

#include <stdio.h>

int main() {
    int grade = 85;
    char *result = grade >= 50 ? "Pass" : "Fail";
    printf("You %s the exam.\n", result);

    return 0;
}

This code assigns a string pointer variable based on the condition. If the grade is greater than or equal to 50, it assigns "Pass"; otherwise, it assigns "Fail".

Example 5: Using Ternary Operator with Arrays

The ternary operator can also be used in conjunction with arrays:

#include <stdio.h>

int main() {
    int array[2] = {10, 20};
    int index = 1;
    printf("Value: %d\n", index < 2 ? array[index] : -1);

    return 0;
}

This code uses the ternary operator to perform a safe array lookup. If 'index' is within the array bounds, it returns the value at that index; otherwise, it returns -1.

Ternary Operator Vs. if...else Statement in C

The ternary operator and if-else statements in C are used for conditional operations. They evaluate certain conditions and execute different codes based on whether they are true or false.

While both have specific use cases, clear distinctions can influence which method to use for conditional logic. Let's first discuss these differences in detail and then follow up with a comparison table for a snapshot understanding.

Ternary Operator

A ternary operator is essentially a shorthand version of an if-else statement. It provides a way to make your code more compact, condensing the if-else statement into a single line of code. This operator can be especially useful when assigning values to variables based on a condition.

Here's a sample usage of the ternary operator:

#include <stdio.h>

int main() {
    int a = 10, b = 20;

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

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

In this example, the ternary operator checks whether 'a' is greater than 'b'. If the condition is true, 'a' is assigned to 'max'. If the condition is false, 'b' is assigned to 'max'.

if...else Statement

On the other hand, if-else statements are more flexible and can handle complex logic and multiple conditions better than the ternary operator. They're easier to read, especially when the code block within the if-else construct is large.

Here's how the same problem would be solved using an if-else statement:

#include <stdio.h>

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

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

    printf("The maximum number is %d\n", max);

    return 0;
}

Comparison Table

Criteria

Ternary Operator

if...else Statement

Syntax

More complex, and takes time to get used to

Simple and straightforward

Code Size

More compact, it can be written in a single line

More verbose, requires multiple lines

Readability

Less readable when conditions get complex

More readable, especially with complex conditions

Use-case

Best for simple conditions and quick assignments

Best for complex conditions and multi-step processes

Nesting

Can be nested but reduces readability

Can be nested with ease and maintains readability

Cons Of Using The Ternary Operator In C

While the Ternary Operator in C provides a concise alternative to the if-else statement, overuse or improper use of this operator can lead to some issues. Here are some of the main cons of using the Ternary Operator in C:

1. Readability Issues: The primary disadvantage of the ternary operator is that it can make the code difficult to read, especially for those unfamiliar with the operator. This is especially true when it comes to complex or nested ternary expressions. Overusing ternary operators can make your code seem cluttered and cryptic, making it harder for others (and sometimes even yourself) to understand your logic.

2. Debugging Difficulties: The ternary operator's conciseness can lead to debugging challenges. Identifying and resolving errors in a line of code with a ternary operator may be more difficult compared to a more explicit if-else statement.

3. Misuse of Ternary Operators: Ternary operators are not meant to replace every if-else statement in your code. They're best suited for simple, straightforward conditional logic. Using ternary operators for complex conditions or procedures can lead to complicated, hard-to-read code.

4. Limited Use Cases: Unlike if-else statements, the ternary operator is not suitable for conditions that need to execute blocks of code or multiple statements. It's designed for simple, single-statement conditions.

5. Negatively Affects Maintainability: Code maintainability is crucial to software development. A code that is easy to read and understand can be updated and fixed more easily. Overuse of ternary operators can reduce the maintainability of your code, making it harder for you or other developers to update or expand on your code in future.

Practice Problems On Arithmetic Operator In C

Here are some of the problems that you can look at to get a better grasp of how C ternary operators work:

Problem 1: Write a C program that uses the ternary operator to determine if a year is a leap year or not.

Problem 2: Write a C program that uses the ternary operator to determine the quadrant in which a given coordinate point lies.

Problem 3: Write a C program that uses the ternary operator to determine the type of a triangle given the lengths of its sides (equilateral, isosceles, or scalene).

Problem 4: Write a C program that uses the ternary operator to check if a person is eligible to vote or not.

Problem 5: Write a C program that uses the ternary operator to calculate the grade of a student based on their average score. The grade should be calculated as follows:

  • Grade A if the score is 90 or above
  • Grade B if the score is between 70 and 89
  • Grade C if the score is between 50 and 69
  • Grade F if the score is less than 50

Conclusion

The Ternary Operator in C is a powerful tool that simplifies code and improves efficiency by making it more compact. To effectively utilise the ternary operator, it is crucial to understand its syntax and working. While its conciseness can be advantageous, it's important to avoid overuse, as it can result in code that is challenging to understand and debug.

If you've found the Ternary Operator in C intriguing and wish to explore the vast world of programming further, consider upGrad's comprehensive DevOps Engineer Bootcamp to dive deep into programming, hone your skills, and emerge a coding wizard!

FAQs

1. What is the ternary Operator in C symbol?

The Ternary Operator in C uses the '?' and ':' symbols. The general syntax is condition ? value_if_true : value_if_false.

2. How many ternary operator in C?

In C, there is only one ternary operator, which is the conditional operator (? :).

3. Can you provide an example of the ternary operator in C?

Yes, here is a simple example:

int a = 5, b = 10;
int max = (a > b) ? a : b;

In this code, max will have the value of b because a is not greater than b. Therefore, the condition is false.

4. Is it good practice to always use the ternary operator in C for conditional operations?

While the ternary operator can make your code more concise, using it excessively or for complex conditions can lead to code that's hard to read and debug. For more complex conditions, traditional if-else statements may be more suitable.

5. Can the ternary operator in C be nested?

Yes, the Ternary Operator in C can be nested. However, this can make the code complicated and difficult to read, and it's generally advisable to avoid it when possible.

Pavan

PAVAN VADAPALLI

Director of Engineering

Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working … Read More

Get Free Career Counselling
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...