< Prev
Next >

# C++ Conditional Operator

In this article, we are going to explain another operator provided by C++, conditional operator. It is also called ternary operator because it has three operands, such as
• Boolean-condition.
• First expression.
• Second expression.

## Syntax of conditional operator -

``````boolean-condition ? first expression : second expression;
```
```

## Rules of conditional operator -

• If the result of boolean-condition is true, first expression will be executed and its value is returned.
• If the result of boolean-condition is false, second expression will be executed and its value is returned.
• First expression and second expression must result in a value.

## Conditional operator example.

``````// Conditional Operator Example i C++

#include<iostream>

using namespace std;

int main()
{
int a=10, b=20;

int result =a>b ? 10 : 20;
cout<<"Result1 is : " <<result <<"\n";

result = a>b ? 10 : 100.50;
cout<<"Result2 is : " <<result <<"\n";

char ch = a>b ? 'y' : 'n';
cout<<"Result3 is : " <<ch <<"\n";

result = 100>=99 ? 100 : 99;
cout<<"Result4 is : " <<result <<"\n";

return 0;
}
``````
Output
``````Result1 is 20
Result2 is 100
Result3 is n
Result4 is 100``````

## The first expression of a conditional operator can be left blank

``````//Conditional Operator in C++

#include<iostream>

using namespace std;

int main()
{
int a=10, b=20;

int result = a>b ? 0 : 10;
cout<< "Result1 is : " << result << "\n";

char ch = a < b ? : 'n'; 	// Intentionally leaving the first expression
cout<< "Result2 is : " << ch << "\n";

return 0;
}``````

## Output-

``````Result1 is 10
Result2 is ☺``````

In the last code, we have intentionally left out the first expression and the program has still compiled and executed successfully.

## The second expression of a conditional operator cannot be left blank

``````#include<stdio.h>

using namepsace std;

int main()
{
result = 9<2 ? 9 : ;
cout<< "Result2 is : " << result;
}``````

## Output-

``````func41.c:5:20: error: expected expression before ';' token
result = 9<2 ? 9 : ;
^``````

In the last code, we have intentionally left out the second expression and the compiler has thrown an error, complaining that the second expression is expected before semicolon.

## An expression of a conditional operator can be a method call.

Any expression of a conditional operator could even be a call to a function but this function must return a value.

``````#include<iostream>

using namespace std;

int main()
{
char fun(); // function prototype declaration

char result = 100>99? fun() : 'n'; // Calling function fun() in the first expression
cout << "Result is " << result;

return 0;
}

char fun()
{
return 'y';
}
``````

## Output-

``Result is y``

In the last code, the first expression of the conditional operator is a call to a function fun(), which has returned us a char y.

< Prev
Next >
< Logical Operators in C++
Scope Resolution Operator >