# Conditional-Operator or Ternary-Operator in CPlusPlus

The Conditional-Operator evaluates an expression. If that expression is true then it will generate one output but if that expression is false then it will generate another output.

Here is an example: 3+2 = 9 ? a : b

In this example you ask a question (is 3 + 2 equal to 9 or not?) and you say if this expression is true choose the option (a) and if the expression is false choose the option (b). Since (3+2) is equal to (5) and not (9); the person has to choose the option (a).

Quite the same; the general syntax for a Conditional-Operator is as below:

If the condition is true the expression will generate expression 1 and inverse.

Some Examples:

7 = 7 ? 4 : 6 // generates the value 4; because 7 is equal to 7

7+1 = 6 ? 4 : 6 // generates the value 6; because 7+1 is not equal to 6

3 > -4 ? a : b // generates the value a; because 3 is greater than (-4)

5 < 9 && 5 > 6 ? a : b // generates the value b; because a logical AND is used in the expression both the conditions (5<9) and (5>6) should be true so that the expression become true.

The Conditional-Operator (?) is also called to be a ternary operator. Because it needs three operands to work on.

**See Also:** Basic Operators in Programming Languages

The Conditional-Operator is also used to replace an if-else statement.

The general syntax for an if – else statement is:

1 2 3 4 5 |
if (condition) { result 1; } else { result 2; } |

For Example:

1 2 3 4 5 |
if ( 8<10 ) { cout << “The expression is true!” << endl; } else { cout << “The expression is false!” << endl; } |

The output for the above code will be:

1 |
The expression is true! |

## Programs Demonstrating Conditional-Operator:

Below you can find a program which demonstrates the idea of Conditional-Operator;

1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> using namespace std; int main () { int a, b,c; a = 8; b = 12; c = a > b ? a : b; cout << “The greater number is: “ << c << endl; return 0; } |

Output:

1 |
The greater number is: 12 |

**See Also:** Function OverLoading in C++

WAP to find the biggest out of 3 different numbers entered by the user in C Language:

1 2 3 4 5 6 7 8 9 10 11 12 |
#include<stdio.h> #include<conio.h> void main () { int A, B, C, Biggest; clrscr (); printf ("Enter three different numbers:"); scanf ("%d%d%d",&A,&B,&C); Biggest = A>B?(A>C?A:C):(B>C?B:C); printf ("The biggest number is = %d",Biggest); getch (); } |

Output:

Pingback: Decision Making Structures in CPlusPlus | CodeJow()