Sams Teach Yourself C++ in 21 Days

(singke) #1
These two statements also are equivalent:
if (!x) // if x is false (zero)
if (x == 0) // if x is zero
The second statement, however, is somewhat easier to understand and is more explicit if
you are testing for the mathematical value of xrather than for its logical state.

94 Day 4


DOput parentheses around your logical
tests to make them clearer and to make
the precedence explicit.
DOuse braces in nested ifstatements to
make the elsestatements clearer and to
avoid bugs.

DON’Tuse if(x)as a synonym for
if(x != 0); the latter is clearer.
DON’Tuse if(!x)as a synonym for
if(x == 0); the latter is clearer.

DO DON’T


The Conditional (Ternary) Operator ......................................................................


The conditional operator (?:) is C++’s only ternary operator; that is, it is the only opera-
tor to take three terms.
The conditional operator takes three expressions and returns a value:
(expression1)? (expression2) : (expression3)
This line is read as “If expression1is true, return the value of expression2; otherwise,
return the value of expression3.” Typically, this value is assigned to a variable. Listing
4.9 shows an ifstatement rewritten using the conditional operator.

LISTING4.9 A Demonstration of the Conditional Operator
1: // Listing 4.9 - demonstrates the conditional operator
2: //
3: #include <iostream>
4: int main()
5: {
6: using namespace std;
7:
8: int x, y, z;
9: cout << “Enter two numbers.\n”;
10: cout << “First: “;
11: cin >> x;
12: cout << “\nSecond: “;
13: cin >> y;
14: cout << “\n”;
Free download pdf