'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: Sep 24, 2023
Easy

Conditional 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

Do you know what is a conditional operator in C and how it can make our code concise? In this article, we will discuss about the conditional operator in C language. We will discuss the syntax of the conditional operator, its uses, associativity, and how it differs from an if-else statement.

conditional operator in c

Moving forward, let’s first understand about the conditional operator.

What is a Conditional Operator in C?

The conditional operator in C is also known as the ternary conditional operator. It is denoted with a “?” (question mark) and a colon “:”. It is often used as a shortcut for an if-else statement. It allows us to select one of two expressions according to the provided condition. Let’s say we have two options and a condition. If the condition is true under any circumstance, we select one option from the two provided conditions, and if not, the latter is preferred.

Syntax of Conditional Operator in C

Condition ? if_true : if_false;

 

In the above syntax, the condition is a boolean expression that evaluates true or false. If this condition is true, then the value of ‘if_true’ is selected. Otherwise, the ‘if_false’ value is selected.

Example,

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

 

In the example above, the condition ‘a>b’ checks if ‘a’ is greater than ‘y’. If the condition is true, the value of the entire expression above is equated to ‘a’. Otherwise, it is ‘b.’ The result is assigned to the variable ‘ninjaVar’.

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

Working of Conditional Operator in C

The working of the conditional operator is mentioned below.

  • The conditional operator works by evaluating the provided condition that is mentioned before ‘?’ (as shown in the above example). 
     
  • If the condition turns out to be true, then the expression after “?” is executed.
     
  • But if the condition is false, then the expression mentioned after “:” is executed.
     
  • Therefore, according to this, the resulting expression is returned. The result can also be stored in a variable.

Flowchart of Conditional Operator in C

Flowchart of Ternary Operator

Examples of Conditional Operator in C

Let's discuss some of the examples of conditional operators in C.

Example 1: Finding the maximum value


Code

#include <stdio.h>

int main() {
    
    // Initialising Variables
    int NinjaVar1=5;
    int NinjaVar2=9;


    // Storing the result of the conditional operator in variable
    int maxVal=(NinjaVar1>NinjaVar2)? NinjaVar1:NinjaVar2;
    
    // Printing the result
    printf("Maximum value is:%d",maxVal);
    
    return 0;
}


Output

output

 

Explanation 

In the above example, we have initialized two variables, ‘NinjaVar1’ and ‘NinjaVar2’. The conditional operator results in the maximum value by evaluating the specified condition i.e., ‘(NinjaVar1>NinjaVar2)’. The resulting value is stored in the variable ‘maxVal’ and then printed.

Example 2: Conversion of a boolean value to a string


Code

#include <stdio.h>

int main() {
    
    // Initialising Variables
    int NinjaVar=1;

    // Storing the result of the conditional operator in variable
    char* result=(NinjaVar)? "True" :"False";
    
    // Printing the result
    printf("The result is:%s",result);
    
    return 0;
}


Output

output

Explanation:

In the above example, we have initialized the variable, ‘NinjaVar’. In the statement string result=(NinjaVar)? "True" :"False"; ’ the value of the 'result'  will beTrue’, as NinjaVar is also ‘True’ (1).

Also see, Floyd's Triangle in C

Difference between Conditional Operator in C and if-else Statement in C

The conditional operator is different from an if-else statement in the following ways: 

  • Syntax: The conditional operator has a concise syntax as compared to the if-else statement.
     
  • Use case: The conditional operator is handy when assigning a value to a variable according to a condition. On the other hand, if-else, the statement is more useful when executing different statement sets based on a specific condition.
     
  • Nesting: The if-else statements can be nested inside other if-else statements. This helps in creating a more complex decision-making structure. The conditional operator can also be nested. But it makes our code hard to understand.

Associativity of Conditional Operator in C

The associativity of the conditional operator is said to be from right to left. Suppose there are multiple conditional operators in an expression. The expression will be evaluated from right to left.

For example,

Condition1 ? expression1 : Condition2 ? expression2: expression3

 

ninjaVar1 > ninjaVar2 ? ninjaVar1 : ninjaVar2 > ninjaVar3 ? ninjaVar2: ninjaVar3

 

Condition1 = ninja1 > ninja2
Condition2 = ninja2 > ninja3  // evaluated first


In the expression above, we have two conditional operators. According to the associativity rule, first, the rightmost conditional operator will be evaluated. Therefore the expression  ‘ninjaVar2 > ninjaVar3 ? ninjaVar2: ninjaVar3’ will be evaluated first.

The leftmost conditional operator ‘ninjaVar1 > ninjaVar2 ? ninjaVar1 will be evaluated using the result of   ‘ninjaVar2 > ninjaVar3 ? ninjaVar2 : ninjaVar3’ . This means that if ninjaVar1 is greater than ninjaVar2, then the entire expression will be given the value ninjaVar1, and if it is false, then the expression will have the result of the previous expression.

Use of parentheses to evaluate the conditional operator correctly when there are multiple operators in an expression is essential.

Nested Conditional Operator

We can also use nested conditional operators in C. It basically means that we have to apply the concept of the conditional operator inside an already defined conditional operator. Let us study this with an example below:

  • C

C

#include <stdio.h>

int main() {
  // Write C code here
  int a=5;
  int b=10;
  int ans;
  ans=(a==5)?(b==12?4:8):12;
  printf("The value of ans is %d", ans);
 
  return 0;
}

 

Output

output for nested conditional operator in c

We can see that the value assigned to the variable ‘ans’ is 8. In the first condition, it proves to be true, so it goes inside the nested conditional operator, where the condition proves false, and hence the value assigned is 8.

Uses of the Conditional Operator in C

There are various uses for conditional operator in C. Some of them are mentioned below.
 

  • The conditional operator provides a compact way for evaluating a certain condition and reduces the size of the code.
     
  • You can even use it for terminating a loop according to the specific condition.
     
  • The conditional operator can be used for validating user input. Validating user input means that the input that is provided meets a certain requirement. For example, the criteria that only a person above 18 can give vote.
     
  • It can also be used in return statements. You can use it in a function for returning a value according to the specific condition.
     
  • You can use it for assigning a value to a variable based on a provided condition.
     
  • You can use the conditional operator for concatenating (merging) two strings according to the specified condition.

Frequently Asked Questions

What is a conditional operator in C? 

The conditional operator in C is also known as the ternary conditional operator. It is denoted with a “?” (question mark) and a colon “:”. It is often used as a shortcut for an if-else statement.

What is an example of a conditional operator? 

The conditional operator can be used for assigning a value to a variable based on a provided condition. For example, when comparing the values of two variables, the result of the conditional operator can be directly stored in a variable.

What are ternary operators in C? 

Ternary operators in C can also be referred to as conditional operators that can be used instead of an ‘if-else’ statement. It accepts three operands, i.e., the condition and expression that must be executed if the condition is true and another expression that is executed if the condition is false.

What is the purpose of the conditional operator?

The conditional operator helps us evaluate a condition and returns a value based on the two values provided. It is often used as a short-hand way of writing an if-else statement.

Conclusion

We hope this article helped you understand conditional operator in C. We have discussed the syntax of the conditional operator, its uses, associativity, and how it differs from an if-else statement. Refer to our Operators article to better understand about operators in C language.

You will find straightforward explanations on almost every topic on this platform. You can read more such articles on our platform, Coding Ninjas Studio. So take your learning to the next level with Coding Ninjas. 

Happy Coding! 

Previous article
Pre Increment and Post Increment in C
Next article
Syntax of Switch Statement 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