Last Updated: Jul 13, 2024
Easy

Conditional Operator in C

Table of contents
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

The conditional operator in C, also known as the ternary operator, is a concise way to perform conditional evaluations. It is the only operator in C that takes three operands and follows the syntax: condition ? expression1 : expression2;. If the condition evaluates to true, expression1 is executed; otherwise, expression2 is executed. This operator provides a shorthand for simple if-else statements, making the code more readable and efficient.

conditional operator in c

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’.

Another Version of the Conditional Operator in C

The conditional operator in C, also known as the ternary operator, is a compact and efficient way to make decisions within an expression. It uses the syntax condition ? expression1 : expression2;, where condition is evaluated first. If condition is true, expression1 is returned; otherwise, expression2 is returned. This operator simplifies code by replacing simple if-else statements and can enhance readability and reduce code length.

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;
}
You can also try this code with Online C Compiler
Run Code


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;
}
You can also try this code with Online C Compiler
Run Code


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
You can also try this code with Online C Compiler
Run Code

 

ninjaVar1 > ninjaVar2 ? ninjaVar1 : ninjaVar2 > ninjaVar3 ? ninjaVar2: ninjaVar3
You can also try this code with Online C Compiler
Run Code

 

Condition1 = ninja1 > ninja2
Condition2 = ninja2 > ninja3  // evaluated first
You can also try this code with Online C Compiler
Run Code


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;
}
You can also try this code with Online C Compiler
Run Code

 

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.

What are the three conditional operators?

The three conditional operators in C are:

  1. Ternary Operator (?:): Evaluates a condition and returns one of two values.
  2. Logical AND (&&): Returns true if both operands are true.
  3. Logical OR (||): Returns true if at least one operand is true.

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, Code360.

Happy Coding!