Conditional Operator in C++ | Ternary operator in C++

conditional operator in C++

Conditional Operator in C++ | Ternary operator in C++



?: symbol represents conditional operator in C++. Conditional operator is also known as ternary operator as this operator has three operands.  It always tests a condition. Depending upon the result of condition, a specific instruction get executed.

Syntax:

Condition? S1: S2;

Condition is a conditional expression.

S1 refers to statements of C++ which will execute if condition is true.

S2 refers to statements of C++ which will  execute if condition is false.

//Program to demonstrate the use of conditional operator.

#include<iostream> 
using namespace std;
int main()
{
  int n1=10,n2=3,n3;
  n3=n1>n2?n1:n2;
  cout<<“\nn3=“<<n3;
 return(0);  
}

Output:

n3=15

** In the above program, expression n3=n1>n2?n1:n2 is evaluated. Here variable n1 contains 10 and n2 contains 5. Condition n1>n2 is true, so statement after question mark (?) will be evaluated and n3 will contain value of n1 i.e. 15.



Spread the love
Lesson tags: Conditional Operator in C++, Ternary operator in C++
Back to: C++ Programming Notes
Spread the love