Tom Kelliher, CS17
Apr. 15, 1996
C/C++'s only trinary operator!
(expression_1) ? expression_2 : expression_3
Examples:
int i, j; int largest; cout << "Enter two integer values: "; cin >> i >> j; largest = (i > j) ? i : j; cout << largest << " is the largest value you entered.\n";
int sodaCount;
cout << "How many sodas do you want? ";
cin >> sodaCount;
cout << "You have requested " << sodaCount
<< ((sodaCount == 1) ? "soda.\n" : "sodas.\n");
Simple predicates connected with logical operators:
&&.
||.
Unary operator.
Truth table:
Binary operator.
Truth table:
Binary operator.
Truth table:
!(a == b) --> a != b !(a != b) --> a == b !(a < b) --> a >= b !(a <= b) --> a > b !(expr1 && expr2) --> (!expr1) || (!expr2) !(expr1 || expr2) --> (!expr1) && (!expr2)How could we prove these?
+ - ++ -- (type) ! (right assoc.)
* / %
+ -
<< >>
< <= > >=
== !=
&&
||
?: (right assoc.)
= += -= *= /= %= (right assoc.)
We already have multiway selection with the if:
char letterGrade(int numberGrade)
{
if (numberGrade < 60)
return 'F';
else if (numberGrade < 70)
return 'D';
else if (numberGrade < 80)
return 'C';
else if (numberGrade < 90)
return 'B';
else
return 'A';
}
switch statement allows you to ``jump'' to a label in a following compound block.
break statement allows you to ``jump'' out of a compound block --- only for loops and switch blocks.
Example:
int n;
cout << "Enter n: ";
cin << n;
switch (n)
{
case 1:
case 2:
cout << "**\n";
break;
case 3:
cout << "***\n";
break;
case 4:
case 5:
case 6:
cout << "****\n";
break;
default:
cout << "******\n";
break;
}
Exercises 2, 6, 7, and 10 on pg. 421.