Ternary operator:
Read the following code:
IF (A> B)
Z = A;
the else
Z = B;
the code can be simplified toz=(a>b)?a:b;
z = (a> b) a:? b; the formula 3 is a conditional expression with the operation target, wherein the? : Add operator called three mesh y
Ternary operator priority: the execution direction from right to left:
z = (a> b) a: b; equivalent to z = a> b a:?? (a> b a: b?)
Ternary operator is typed questions:
Code:
#include<iostream>
using namespace std;
int main()
{
int a=1;
float b=1.41;
cout<<(a>b?a:b)<<endl;
return 0;
}
Enter the result:
Ternary operator in the use of character variables:
#include<iostream>
using namespace std;
int main()
{
char a;
cin>>a;
cout<<(a=(a>='A'&&a<='Z')?(a+32):a)<<endl;
return 0;
}