The ones who are crazy enough to think they can change the world are the ones who do.
- Steve Jobs

C Conditional or Ternary Operator

The conditional operator is sometimes called a ternary operator because it involves three operands. It is best understood by considering the following example
younger = son < father ? 18 : 40;

In the above example, son's age is 18 whereas father's age is 40. But we need the younger age so we make use of conditional operator to extract least age.

Conditional or Ternary Operator

Syntax of Conditional Operator in C

  • The conditional operator contains a condition followed by two statements or values.
  • If the condition is true the first statement is executed, otherwise the second statement or value.
Syntax
condition ? (value 1) : (value 2)

How Conditional Operator Works

Conditional operator performs nothing more special. It is the abstraction of if else statement. Consider the following example how Condtional Operator works
younger = true ? 18 : 40;

If the logical expression resulted true, 18 will be stored in a variable younger.
younger = false ? 18 : 40;

If the logical expression resulted true, 40 will be stored in a variable younger.

Program without Conditional Operator

Here we are to find the least age and store it in a variable younger_age without using Conditional operator.

noternary.c
#include <stdio.h> //header file section
int main() //main section
{
int son = 18;
int father = 40;
int younger_age;
if(son < father)
younger_age = son;
else
younger_age = father;
printf("%d is the younger age", younger_age);
return 0;
}
  • 18 is the younger age

Note:

Here the code looks more verbose as we make use of if else statement.

Program Using Conditional Operator

Here we are to find the least age and store it in a variable younger_age using Conditional operator.

ternary.c
#include <stdio.h> //header file section
int main() //main section
{
int son = 18;
int father = 40;
int younger_age;
younger_age = son < father ? son : father;
printf("%d is the younger age", younger_age);
return 0;
}
  • 18 is the younger age

Note:

In line 7, Conditional Operator is get used to reduce the size of the program.

Report Us

We may make mistakes(spelling, program bug, typing mistake and etc.), So we have this container to collect mistakes. We highly respect your findings.

Report