Conditional Operator in C

By | February 18, 2023

Prerequisite – Operators in C
The conditional operator in C is a ternary operator that is used to evaluate a boolean expression and return one of two values depending on whether the expression is true or false.

Syntax:
The syntax of the conditional operator is as follows:

condition ? value_if_true : value_if_false;

Here, condition is a boolean expression that is evaluated. If the condition is true, then the value of value_if_true is returned, otherwise the value of value_if_false is returned.

Example:
Here’s an example code that demonstrates the use of the conditional operator in C:

#include <stdio.h>

int main() {
    int a = 10, b = 5, c;
    
    c = (a > b) ? a : b;
    printf("The larger number is: %d\n", c);
    
    return 0;
}

In this example, we declare three integer variables a, b, and c. We then use the conditional operator to assign the larger of the two numbers a and b to c. The boolean expression a > b is evaluated, and if it is true, the value of a is returned, otherwise the value of b is returned. The result is then assigned to c, which is printed to the console.

The output of this program will be:

The larger number is: 10

As you can see, the value of c is assigned the value of a (10), since a is greater than b (5).

Please write comments below if you find anything incorrect, or you want to share more information about the topic discussed above. A gentle request to share this topic on your social media profile.

Author: Mithlesh Upadhyay

I hold an M.Tech degree in Artificial Intelligence (2023) from Delhi Technological University (DTU) and possess over 4 years of experience. I worked at GeeksforGeeks, leading teams and managing content, including GATE CS, Test Series, Placements, C, and C++. I've also contributed technical content to companies like MarsDev, Tutorialspoint, StudyTonight, TutorialCup, and Guru99. My skill set includes coding, Data Structures and Algorithms (DSA), and Object-Oriented Programming (OOPs). I'm proficient in C++, Python, JavaScript, HTML, CSS, Bootstrap, React.js, Node.js, MongoDB, Django, and Data Science.