• Home
  • Conditional Operator in C language

Conditional Operator in C language

In C, the conditional operator (also known as the ternary operator) is used to perform a conditional operation that returns one of two values based on a condition. The syntax for the conditional operator is:

(condition) ? value1 : value2

If the condition is true, the operator returns value1. If the condition is false, the operator returns value2. For example:

int a = 5;
int b = 2;
int c = (a > b) ? a : b; // c is now 5

Here, the condition (a > b) is true, so the operator returns a, which is 5.

The conditional operator can be used to simplify if-else statements, as shown in the following example:

int a = 5;
int b = 2;
int c; if (a > b) { c = a; } else { c = b; }

This code can be rewritten using the conditional operator as follows:

int a = 5;
int b = 2;
int c = (a > b) ? a : b;

It is important to use the correct syntax when using the conditional operator, as using the wrong syntax can result in errors or unexpected results in your code.