Conditional or Ternary Operator ( - ) in C - C++
Conditional or Ternary Operator ( - ) in C - C++
Syntax:
The conditional operator is of the form
if(Expression1)
{
variable = Expression2;
}
else
{
variable = Expression3;
}
Since the Conditional Operator ‘?:’ takes three operands to work, hence they are also called ternary operators.
Working:
Here, Expression1 is the condition to be evaluated. If the condition(Expression1) is True then Expression2 will be executed and the result will
be returned. Otherwise, if the condition(Expression1) is false then Expression3 will be executed and the result will be returned.
Example: Program to Store the greatest of the two Number.
C
// C program to find largest among two
// numbers using ternary operator
#include <stdio.h>
int main()
{
// variable declaration
int n1 = 5, n2 = 10, max;
// Largest among n1 and n2
max = (n1 > n2) ? n1 : n2;
// Print the largest number
printf("Largest number between"
" %d and %d is %d. ",
n1, n2, max);
return 0;
}
C++
Output:
Largest number between 5 and 10 is 10.