Open In App

Conditional or Ternary Operator (?:) in C

Last Updated : 03 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The conditional operator in C is kind of similar to the if-else statement as it follows the same algorithm as of if-else statement but the conditional operator takes less space and helps to write the if-else statements in the shortest way possible. It is also known as the ternary operator in C as it operates on three operands.

Syntax of Conditional/Ternary Operator in C

The conditional operator can be in the form

variable = Expression1 ? Expression2 : Expression3;

Or the syntax can also be in this form

variable = (condition) ? Expression2 : Expression3;

Or syntax can also be in this form

(condition) ? (variable = Expression2) : (variable = Expression3);
conditional or ternary operator in c

Conditional/Ternary Operator in C

It can be visualized into an if-else statement as: 

if(Expression1)
{
    variable = Expression2;
}
else
{
    variable = Expression3;
}

Since the Conditional Operator ‘?:’ takes three operands to work, hence they are also called ternary operators.

Note: The ternary operator have third most lowest precedence, so we need to use the expressions such that we can avoid errors due to improper operator precedence management.

Working of Conditional/Ternary Operator in C

The working of the conditional operator in C is as follows:

  • Step 1: Expression1 is the condition to be evaluated.
  • Step 2A: If the condition(Expression1) is True then Expression2 will be executed.
  • Step 2B: If the condition(Expression1) is false then Expression3 will be executed.
  • Step 3: Results will be returned.

Flowchart of Conditional/Ternary Operator in C

To understand the working better, we can analyze the flowchart of the conditional operator given below.

flowchart of conditional/ternary operator in c

Flowchart of conditional/ternary operator in C

Examples of C Ternary Operator

Example 1: C Program to Store the greatest of the two Numbers using the ternary operator

C




// C program to find largest among two
// numbers using ternary operator
  
#include <stdio.h>
  
int main()
{
    int m = 5, n = 4;
  
    (m > n) ? printf("m is greater than n that is %d > %d",
                     m, n)
            : printf("n is greater than m that is %d > %d",
                     n, m);
  
    return 0;
}


Output

m is greater than n that is 5 > 4

Example 2: C Program to check whether a year is a leap year using ternary operator

C




// C program to check whether a year is leap year or not
// using ternary operator
  
#include <stdio.h>
  
int main()
{
    int yr = 1900;
  
    (yr%4==0) ? (yr%100!=0? printf("The year %d is a leap year",yr)
     : (yr%400==0 ? printf("The year %d is a leap year",yr)
         : printf("The year %d is not a leap year",yr)))
             : printf("The year %d is not a leap year",yr);
    return 0;
}
  
//This code is contributed by Susobhan AKhuli


Output

The year 1900 is not a leap year

Conclusion

The conditional operator or ternary operator in C is generally used when we need a short conditional code such as assigning value to a variable based on the condition. It can be used in bigger conditions but it will make the program very complex and unreadable.

FAQs on Conditional/Ternary Operators in C

1. What is the ternary operator in C?

The ternary operator in C is a conditional operator that works on three operands. It works similarly to the if-else statement and executes the code based on the specified condition. It is also called conditional Operator

2. What is the advantage of the conditional operator?

It reduces the line of code when the condition and statements are small.



Previous Article
Next Article

Similar Reads

C++ Ternary or Conditional Operator
In C++, the ternary or conditional operator ( ? : ) is the shortest form of writing conditional statements. It can be used as an inline conditional statement in place of if-else to execute some conditional code. Syntax of Ternary Operator ( ? : )The syntax of the ternary (or conditional) operator is: expression ? statement_1 : statement_2;As the na
3 min read
Max of two numbers without conditional statements, ternary operator or relational operators
Given two integers a and b, the task is to find the greatest of two given numbers without using any conditional statements (such as if and switch), the ternary operator ((condition X)? if X is true: if X is false;) or relational operators (such as &lt;, &gt;, &lt;=, &gt;=, ==, !=). Examples: Input: a = 86, b = 34Output: 86 Input: a = -56, b = -78 O
3 min read
Implementing ternary operator without any conditional statement
How to implement ternary operator in C++ without using conditional statements.In the following condition: a ? b: c If a is true, b will be executed. Otherwise, c will be executed.We can assume a, b and c as values. 1. Using Binary Operator We can code the equation as : Result = (!!a)*b + (!a)*c In above equation, if a is true, the result will be b.
4 min read
C++ | Nested Ternary Operator
Ternary operator also known as conditional operator uses three operands to perform operation. Syntax : op1 ? op2 : op3; Nested Ternary operator: Ternary operator can be nested. A nested ternary operator can have many forms like : a ? b : ca ? b: c ? d : e ? f : g ? h : ia ? b ? c : d : e Let us understand the syntaxes one by one : a ? b : c =&gt; T
5 min read
C/C++ Ternary Operator - Some Interesting Observations
Predict the output of following C++ program. #include &lt;iostream&gt; using namespace std; int main() { int test = 0; cout &lt;&lt; &quot;First  character &quot; &lt;&lt; '1' &lt;&lt; endl; cout &lt;&lt; &quot;Second character &quot; &lt;&lt; (test ? 3 : '1') &lt;&lt; endl; return 0; } One would expect the output will be same in both the print sta
3 min read
C program to check if a given year is leap year using Conditional operator
Given an integer that represents the year, the task is to check if this is a leap year, with the help of Ternary Operator. A year is a leap year if the following conditions are satisfied: The year is multiple of 400.The year is a multiple of 4 and not a multiple of 100. Following is pseudo-code if year is divisible by 400 then is_leap_year else if
1 min read
C# Program for Nested Conditional Operator
Inner conditional operator can be used in any block,it shows like (a&gt;b)?((a&gt;c)?a:c):(b&gt;c?b:c). Here we input three numbers and finding the largest number using nested conditional operator. Syntax: (logical_test1) ? ((logical_test2)? True_block : false_block) : false_block_outer; By the above conditional operator, it checks the condition on
2 min read
Set a variable without using Arithmetic, Relational or Conditional Operator
Given three integers a, b and c where c can be either 0 or 1. Without using any arithmetic, relational and conditional operators set the value of a variable x based on below rules - If c = 0 x = a Else // Note c is binary x = b. Examples: Input: a = 5, b = 10, c = 0; Output: x = 5 Input: a = 5, b = 10, c = 1; Output: x = 10 Solution 1: Using arithm
2 min read
Maximum of four numbers without using conditional or bitwise operator
Given four numbers, print the maximum of the 4 entered numbers without using conditional or bitwise operator (not even ternary operators). Examples: Input : 4 8 6 5Output : 8Input : 11 17 8 17Output : 17 We use the fact that value of "(x - y + abs(x - y))" will be 0 of x is less than or equal to y. We use this value as index in an array of size 2 t
4 min read
deque::operator= and deque::operator[] in C++ STL
Deque or Double ended queues are sequence containers with the feature of expansion and contraction on both the ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements at the end, and also the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed. deque::operator= This operator
4 min read
Operator Overloading '&lt;&lt;' and '&gt;&gt;' operator in a linked list class
Prerequisite: Operator Overloading in C++, Linked List in C++ C++ comes with libraries that provide ways for performing Input and Output. In C++, Input and Output are performed as a sequence of bytes, also known as streams. Input and Output stream are managed by the iostream library. cin and cout are the standard objects for the input stream and ou
4 min read
Why overriding both the global new operator and the class-specific operator is not ambiguous?
The below section deals about overload resolution as it helps in the fundamentals of overloading and overriding. Predict the output: C/C++ Code #include &lt;iostream&gt; using namespace std; class Gfg { public: void printHello() { cout &lt;&lt; &quot;hello gfg-class specific&quot; &lt;&lt; endl; } }; void printHello() { cout &lt;&lt; &quot;hello gf
5 min read
3-way comparison operator (Space Ship Operator) in C++ 20
The three-way comparison operator "&lt;=&gt;" is called a spaceship operator. The spaceship operator determines for two objects A and B whether A &lt; B, A = B, or A &gt; B. The spaceship operator or the compiler can auto-generate it for us. Also, a three-way comparison is a function that will give the entire relationship in one query. Traditionall
3 min read
vector::operator= and vector::operator[ ] in C++ STL
Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. vector::operator=This operator is used to assign new contents to the container by replacing the existing contents. It also modifies the size according to the new
4 min read
Arrow Operator vs. Dot Operator in C++
In C++, we use the arrow operator (-&gt;) and the dot operator (.) to access members of classes, structures, and unions. Although they sound similar but they are used in different contexts and have distinct behaviours. In this article, we will learn the key differences between the arrow operator and the dot operator in C++ and clarify the confusion
3 min read
Game Theory in Balanced Ternary Numeral System | (Moving 3k steps at a time)
Just like base 2 Binary numeral system having 0s and 1s as digits, Ternary(Trinary) Numeral System is a base 3 number system having 0s, 1s and -1 as digits. It's better to use alphabet 'Z' in place of -1, since while denoting full ternary number -1 looks odd in between 1s and 0s. Conversion of decimal into Balanced Ternary: As in binary conversion,
14 min read
Convert ternary expression to Binary Tree using Stack
Given a string str that contains a ternary expression which may be nested. The task is to convert the given ternary expression to a binary tree and return the root.Examples: Input: str = "a?b:c" Output: a b c a / \ b c The preorder traversal of the above tree is a b c. Input: str = "a?b?c:d:e" Output: a b c d e a / \ b e / \ c d Approach: This is a
10 min read
Balanced Ternary Number System
As we already know, a Binary number system is a number system that has only 2 digits in it, i.e. 0 and 1. Similarly, we also know that a Ternary number system is a number system that has only 3 digits in it, i.e. 0, 1, and 2. In this article, we will learn about Balanced Ternary Number System. A balanced ternary number system is a numeral system th
5 min read
How to implement text Auto-complete feature using Ternary Search Tree
Given a set of strings S and a string patt the task is to autocomplete the string patt to strings from S that have patt as a prefix, using a Ternary Search Tree. If no string matches the given prefix, print "None".Examples: Input: S = {"wallstreet", "geeksforgeeks", "wallmart", "walmart", "waldomort", "word"], patt = "wall" Output: wallstreet wallm
15+ min read
Ternary Search in C
When searching for a specific element in a sorted dataset, many programmers are familiar with binary search. Binary search efficiently narrows down the search space by dividing it into two halves repeatedly. But there's another search algorithm that can be even more efficient in certain scenarios. Ternary search is a searching algorithm that effici
4 min read
Output of C programs | Set 55 (Ternary Operators)
Predict the output of below programs Question 1 #include &lt;stdio.h&gt; int main() { int x, a = 0; x = sizeof(a++) ? printf(&quot;Geeks for Geeks\n&quot;) : 0; printf(&quot;Value of x:%d\n&quot;, x); printf(&quot;Value of a:%d&quot;, a); return 0; } Output: Geeks for Geeks Value of x:16 Value of a:0 Explanation: sizeof is a compile-time operator,
4 min read
Ternary Search in C++
Ternary search is an efficient search algorithm used to find an element in a sorted array. It is a more efficient version of the binary search. In this article, we will learn how to implement the ternary search in C++. How Ternary Search Works?Ternary search divides the array (or search space) into three parts by calculating two midpoints, then it
4 min read
Ternary number system or Base 3 numbers
A number system can be considered as a mathematical notation of numbers using a set of digits or symbols. In simpler words, the number system is a method of representing numbers. Every number system is identified with the help of its base or radix. For example, Binary , Octal , Decimal and Hexadecimal Number systems are used in microprocessor progr
10 min read
Print "Even" or "Odd" without using conditional statement
Write a program that accepts a number from the user and prints "Even" if the entered number is even and prints "Odd" if the number is odd. You are not allowed to use any comparison (==, &lt;,&gt;,...etc) or conditional statements (if, else, switch, ternary operator,. Etc). Method 1 Below is a tricky code can be used to print "Even" or "Odd" accordi
4 min read
Conditional wait and signal in multi-threading
What are conditional wait and signal in multi-threading? Explanation: When you want to sleep a thread, condition variable can be used. In C under Linux, there is a function pthread_cond_wait() to wait or sleep. On the other hand, there is a function pthread_cond_signal() to wake up sleeping or waiting thread. Threads can wait on a condition variabl
2 min read
Conditionally assign a value without using conditional and arithmetic operators
Given 4 integers a, b, y, and x, where x can assume the values of either 0 or 1 only. The following question is asked: If 'x' is 0, Assign value 'a' to variable 'y' Else (If 'x' is 1) Assign value 'b' to variable 'y'. Note: - You are not allowed to use any conditional operator (including the ternary operator) or any arithmetic operator (+, -, *, /)
6 min read
Largest of two distinct numbers without using any conditional statements or operators
Given two positive and distinct numbers, the task is to find the greatest of two given numbers without using any conditional statements(if...) and operators(?: in C/C++/Java). Examples: Input: a = 14, b = 15 Output: 15 Input: a = 14, b = 14 Output: 14 Input: a = 1233133, b = 124 Output: 1233133The Approach is to return the value on the basis of the
3 min read
Operands for sizeof operator
The sizeof operator is used to return the size of its operand, in bytes. This operator always precedes its operand. The operand either may be a data-type or an expression. Let's look at both the operands through proper examples. type-name: The type-name must be specified in parentheses. sizeof(type - name) Let's look at the code: C/C++ Code #includ
2 min read
sizeof operator in C
Sizeof is a much-used operator in the C. It is a compile-time unary operator which can be used to compute the size of its operand. The result of sizeof is of the unsigned integral type which is usually denoted by size_t. sizeof can be applied to any data type, including primitive types such as integer and floating-point types, pointer types, or com
3 min read
C++ | Operator Overloading | Question 10
How can we restrict dynamic allocation of objects of a class using new? (A) By overloading new operator (B) By making an empty private new operator. (C) By making an empty private new and new[] operators (D) By overloading new operator and new[] operators Answer: (C) Explanation: If we declare new and [] new operators, then the objects cannot be cr
1 min read