'Coding has over 700 languages', '67% of programming jobs aren’t in the technology industry', 'Coding is behind almost everything that is powered by electricity'
Last Updated: Feb 21, 2024
Easy

Ternary Operator in C

gp-icon
Data structures & algorithms (Beginner to Intermediate)
Free guided path
13 chapters
99+ problems
gp-badge
Earn badges and level up

Introduction

Starting with the C language is a great first step on your journey to becoming a skilled programmer. Why? Because C lays down the fundamental building blocks you'll need for future coding adventures. It's like learning the ABCs before diving into stories and novels. In this article, we're going to explore the Ternary Operator in C - a handy shortcut for making decisions in your code. We'll break down how it works and show you different ways to use it, all with clear examples to guide you along. Get ready to add another tool to your coding toolkit!

Ternary Operator in C

What is Ternary Operator in C?

The term ternary refers to three, symbolising the use of three operands. Thus the name ternary operator in C came up as it requires three operands. 
The ternary operator in C is used to return values according to a condition. The symbol representing the ternary operator in c is the question mark “?”. It can handle only two return values for a given condition. One is if the condition is passed, that is if the condition is true. Another one is when the condition is false.
The flowchart of the ternary operator in C is given below.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Syntax of Ternary Operator in C

The below-given syntax represents how to use a ternary operator in C.

<condition>?<return if statement is true>:<return if statement is false>;


Evaluation of syntax:

  • There are three parameters or operands used with a ternary operator in C.
     
  • First -  the condition to be followed.
     
  • Ternary operator in C (?) is used.
     
  • Second - Statement to be executed if the condition is true.
     
  • Colon is inserted.
     
  • Third - Statement to be executed if the condition is false.
     
  • End of the statement with a semicolon inserted.

Working of C Ternary Operator

A ternary operator in C works on the concept of booleans. 

The ternary operator in C works as follows:

  • Expression 1(before ?) is used to set the condition.
     
  • Expression 2(before :) is executed if the condition is true.
     
  • Expression 3(before ;) is executed if the condition is false.

Flowchart of Conditional/Ternary Operator in C

Below is the flow chart for the ternary operator.

Ternary Operator flow chart

In the above flowchart, if the given condition is true, then the "?" part will get executed, and then it goes to the expression 2. Otherwise, if the given condition is false, then the ":" part will get executed, and it goes to expression 3, and the resultant value of the expression will be assigned to the variable.

Also see, Floyd's Triangle in C

Example of C Ternary Operator

Example 1 - 

See the examples below to understand the working of ternary operators in C.

#include <stdio.h>
int main() 
{
  // Declare the variables
  int age;

  // Take user input
  printf("Enter your age: ");
  scanf("%d", &age);

  // Use ternary operator
  // Use printf function as an operand.
  (age >= 18) ? printf("Eligible to vote"): printf("Not eligible to vote");

  return 0;
}


Input

Enter your age: 19


Output

Output

We infer from the code above that:

  • Expression 1 that is age >=18 (before ?) is the condition
     
  • Expression 2 that is printf(“Eligible to vote”) (before :) is executed if the age entered is greater than or is 18 i.e., satisfies the condition.
     
  • Expression 3 that is printf("Not eligible to vote") (before ;) is executed if the age is less than 18, i.e., does not satisfy the condition.
     

Example 2 - 

Let’s look into another example to get the working of a ternary operator in C completely clear.

#include <stdio.h>
int main() 
{
  // Declare the variables
  int x;

  // Take user input
  printf("Enter a number: ");
  scanf("%d", &x);

  // Use ternary operator
  // Use printf function as an operand.
  (x % 2 == 0) ? printf("The number is even") : printf("The number is odd");

  return 0;
}


Input

Enter a number: 6


Output

Output

We infer from the code above that:

  • Expression 1, that is x % 2 == 0 (before ?), is the condition.
     
  • Expression 2 is printf(“The number is even”) (before :) is executed if the number x is completely divided by two, i.e., satisfies the condition.
     
  • Expression 3 is printf("The number is odd") (before ;) is executed if the number x leaves a remainder when divided by two, i.e., does not satisfy the condition.
     

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

BasisTernary OperatorIf..else statement
SyntaxUses a single-line syntax. Hence it is more concise.Requires multiple lines and more complex syntax.
ReadabilityIt can be less readable for complex conditions or multiple actions.Generally more readable, especially for complex logic or multiple actions.
Number of ConditionsIt is limited to evaluating a single condition.It can evaluate multiple conditions using else-if clauses. 
Return ValuesIt can be used to return values for expressions.It cannot return value directly.
MaintainabilityIt is easier to maintain for simple, self-obtained conditions.It offers maintainability for complex or lengthy conditions.

Usage of Ternary Operator in C

Following are the uses of Ternary Operator in C:

  • Ternary Operator is used to assign values to a variable conditionally. For example, set a variable result to "Pass" if a score is greater than or equal to 33 and "Fail" otherwise.
     
  • It's handy for selecting different messages or outputs based on a condition. For instance, print "Yes" if a condition is true and "No" otherwise.
     
  • Ternary Operator is used to assign values to a variable when the input is missing or invalid.
     
  • Initialize elements of an array conditionally, making it easy to set specific values based on different cases.

 

Also Read - Bitwise Operators in C 

Frequently Asked Questions

What is a ternary operator in C?

The ternary operator in C is a short method of writing an if-else statement. It allows you to make decisions based on a condition and choose between the two statements.

What is an example of a ternary operator?

An example of a ternary operator is int result = (a > b) ? a : b;, which assigns a to result if a is greater than b, and b otherwise. It's a concise way to choose between two values.

What is ternary operator for 3 conditions in C?

The ternary operator in C doesn't directly support 3 conditions in one statement. Instead, you can nest ternary operators like int result = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c); for multiple conditions.

What are the advantages of the conditional operator?

The advantages of the conditional operator include concise code, reduced need for if-else statements, and the ability to embed expressions directly within other statements, leading to clearer and more compact code, especially for simple conditionals.

Conclusion

In conclusion, the ternary operator in C is a powerful and concise tool for making decisions within a single line of code. It offers a compact alternative to the traditional if-else statement when you need to assign a value based on a condition. We have studied what the ternary operator in C is, how the ternary operator in C works, and the different ways to use it. 

Refer to the Below topics for more understanding

 

Happy Learning!

Previous article
Operators in C Programming
Next article
Modulus Operator in C
Guided path
Free
gridgp-icon
Data structures & algorithms (Beginner to Intermediate)
13 chapters
109+ Problems
gp-badge
Earn badges and level up
Live masterclass