Ternary Operator in C – Syntax, Examples and Advantages

Updated on August 6, 2024

Article Outline

Every developer must know about operators. Operators are symbols that perform some operations on operands. In the C language, we have an efficient ternary operator. This article aims to understand the Ternary Operator in the C language. In this post, we will dive deep into this operator.

What is a Ternary Operator in C language?

A Ternary Operator is a condition operator in the C language, also known as a conditional operator. It has three arguments and provides a shorter way to code an if-else statement. It is used extensively in programming, where we need to write short conditional statements.

*Image
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure

Syntax of Conditional /Ternary Operator in C language

The conditional operator form is:

variable = Expression1 ? Expression2 : Expression3; The syntax can also be in this form variable = (condition)? Expression2 : Expression3; Syntax can also be in this form (condition) ? (variable = Expression2) : (variable = Expression3);

Ternary Operator in C

Working as Conditional/Ternary Operator in C

Let’s understand how Ternary Operators work in C language. The following program demonstrates conditional Ternary Operators in C language.

 

Program 

#include <stdio.h> int main() { int a =500, b = 20; int max; max = (a > b) ? a : b; printf("Maximum value is: %d", max); return 0; }

Output

Maximum value is: 500

In this program, we use the ternary operator to find the maximum between two numbers.

Flow Chart for Ternary Operator in C language

 

Flow Chart of Ternary Operator in C language.

 

Start

|

Evaluate Condition

|

|__ Yes (Condition is true) –> Return Value_if_True –> End

|

|__ No  (Condition is false) –> Return Value_if_False –> End

Basic Example of Ternary Operator

In this section, we will see the basic example of the Ternary operator, where we find the highest digits in three numbers.

 

The following program demonstrates the Ternary Operator

 

Program

#include <stdio.h>   int main() { int a = 343, b = 12434; int max = (a > b) ? a : b; printf("The maximum value is %d", max);   return 0; } 

Output 

The maximum value is 12434

Nested Ternary Operator

In this section, we will learn about the nested ternary operator in the C language and find the largest number in three variables.

 

The following program demonstrates the Nested Ternary Operator

 

Progarm

#include<stdio.h> void main() { int a =30, b = 50, c = 100, larg;  larg = (a>b)?((a>c)?a:c):((b>c)?b:c); printf("Largest number is: %d", larg);  }

Output

The largest number is: 100

Using Ternary Operator in Function Arguments

The ternary operator can also be used as a function argument to make your code more readable and compact.

 

The following program demonstrates the ternary operator in function arguments

 

Program

#include <stdio.h>  void find_evenAnd_Odd(int isEven) { printf(isEven ? "Number is evenn" : "Number is oddn"); }  int main() { int num = 7; find_evenAnd_Odd(num % 2 == 0); return 0; }

Output

Number is odd

In this example, we passed the number to check whether it was odd or even. If it is odd, return “Number is Odd;” otherwise, return “Number is even.”

Using Ternary Operator for Variable Assignment

The ternary operator can be used for efficient variable assignment. The following program demonstrates the variable assignment in the ternary operator.

 

Program

#include <stdio.h> // Ternary Operator example in Variable Assignment in int main() { int grade = 14; char *result = grade >= 50 ? "Pass" : "Fail"; printf("You %s the exam.n", result);  return 0; }

Output

You Fail the exam.

In this code, we are checking whether the student passes or fails using the ternary operator.

Using Ternary Operator with Arrays

Arrays can also use the ternary operator. The following program demonstrates arrays with a ternary operator.

 

Program

#include <stdio.h>  int main() { int array[5] = {10, 20,30,50,90}; int index = 1; printf("Value: %dn", index < 2 ? array[index] : -1);  return 0; }

Output

Value: 20

Difference Between Ternary Operator and If…else Statement in C language

 

The following table differentiates the Ternary Operator and If..else Statement

 

It can also be nested.

 

Advantages of using Ternary Operator in C language

The ternary operator, also known as the conditional operator in C language, has several advantages

 

  • Conciseness: Ternary operator code is concise compared to the traditional if-else statement, especially for simple conditional assignments. This can lead to code that is easier to read and understand, as it reduces verbosity.

 

  • Clear Intent: The use of the ternary operator can make the code clearer, especially when the condition and the resulting expression are short and straightforward.

 

  • Efficiency: The ternary operator is a more optimized code compared to equivalent if-else constructs.

Disadvantages of using Ternary Operator in C language

Ternary Operator in C provides a concise alternative to the if-else statement. Overuse of this operator can lead to some issues. The following main disadvantages of using Ternary Operator in C language.

 

  • Readability Issues: The primary disadvantage of the Ternary Operator is that overuse makes the code unreadable for developers who are unfamiliar with it. Overusing ternary operators can make your code seem cluttered and cryptic, making it harder for others( and sometimes even yourself) to understand your logic.

 

  • Debugging Difficulties: Ternary Operators are not meant to replace every if-else statement in your code. They are best suited for simple, straightforward conditional logic, which makes debugging difficult.

 

  • Misuse of Ternary Operators: Ternary Operators cannot replace every if-else condition in your code. Using ternary operators for complex conditions or procedures can lead to complicated, hard-to-read code.

 

  • Negatively Affects Maintainability: Code quality is crucial in software development. A code is an easy-to-read and readable form. It can be fixed more easily than other code. Overusing the ternary operator can make the code unreadable, which negatively impacts software development.

Practice Problem on Ternary Operator in C language.

 

Here are some problems with the Ternary Operator. Let’s consider some questions regarding the Ternary Operator in the C language.

 

Problem 1:  Write a C program that uses that ternary operator to determine if a year is a lear 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 calculate the grade of a student based on their average score. The grade should be calculated as follows.

 

  • Grade A if the score is 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

In this article, we learned how the Ternary Operator simplifies code and improves efficiency by making it more compact. We also understood the syntax and workings of the ternary operator to effectively use it. The ternary operator can enhance code readability, especially for simple conditional assignments.

Aspect Ternary Operator If…else Statement
Syntax ‘Condition ? exp1 : exp2’ if(condition) {exp1;} else {expr2}’
Usage Compact and concise More verbose
Number of Conditions Supports only one Condition Supports multiple conditions
Number of expressions This operator exactly has two expression They have multiple expressions
Return Value Returns one  of two expression No specific return value
Nesting It can be nested
FAQs
The Ternary Operator in C uses the ‘?’ and ‘.’ symbols. The general syntax is  “ condition ? true: false”.
The ternary operator can make your code more concise. However, using ternary excessively or for complex conditions can make the code hard to debug. For example, where more complex conditions occur, use if-else, which is more suitable.
The ternary operator reduces the complexity and length of the code, making it easy for programmers to identify and correct errors in the code.
The ternary operator can be faster than the if-else statement because it is a single line of code as compared to the if-else statement.

Updated on August 6, 2024

Link
left dot patternright dot pattern

Programs tailored for your success

Popular

IIT Courses

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved