C programming conditional operator (?:)

C programming conditional operator is also known as a ternary operator. It takes three operands. Conditional operator is closely related with if..else statement.

Syntax of C programming conditional operator


(condition) ? expression1 : expression2

If the condition is true then expression1 is executed else expression2 is executed.

c programming conditional operator

For example:

puts( x > y ? "x is greater" : "y is greater");

Here, puts statement contains as its second argument a conditional expression which evaluates to the string "x is greater" if the condition x > y is true and "y is greater" if the condition is false.It can also be done as

It can also be done as

x > y ? puts("x is greater") : puts("y is greater");

Here, if x > y then puts("x is greater") else puts("y is greater").

The output of both expressions is same.

[adsense1]

Example: C program to check whether the student is pass or fail using conditional operator


#include <stdio.h>

int main()
{
 int mark;
 printf("Enter mark: ");
 scanf("%d", &mark);
 puts(mark >= 40 ? "Passed" : "Failed");
 return 0;
}

Output

Enter mark: 39
Failed

Explanation

The program checks the condition mark >=40, if it is true "Passed" is printed else "Failed".

The above program can be simply done with the help of if...else statement.

#include <stdio.h>

int main()
{
  int mark;
  printf("Enter mark: ");
  scanf("%d", &mark);

  if(mark >= 40)
    printf("\nPassed");
  else
    printf("\nFailed");

  return 0;
}

Output

Enter mark: 39
Failed