A ternary operator is one which contains three operands. The
only ternary operator available in C language is conditional operator pair
"?:". It is the form of C++ Conditional ? : Operator:
exp1 ?
exp2 : exp3 ;
This operator works as follows. Exp1 is evaluated first. If
the result is true then exp2 is executed, otherwise exp3 is executed.
e.g.: a = 10;
b = 15;
x = (a
> b ? a: b)
In this expression value of b will be assigned to x.
C++ program to demonstrate
the Conditional? : Operator
#include
<iostream>
using
namespace std;
int
main (){
int a, b;
cout << "Please enter the value
of a and b." << endl;
cout << "a" << setw
(3) << ": ";
cin >> a;
cout << "b" << setw
(2) << ": ";
cin >> b;
string message = a > b ? "a is larger
than b" : "a is smaller than or equal to b";
cout << Result << endl;
return 0;
}
No comments:
Post a Comment