Home Segments Index Top Previous Next

300: Sidetrip

It is possible to use && instead of an if statement by exploiting the property that the right-side operand of an && expression is evaluated only if the value of the left-side operand is not 0. Thus, the following two expressions are equivalent:

if (temperature > 50) cout << "It is too hot!" << endl; 
(temperature > 50) && cout << "It is too hot!" << endl; 

Similarly, it is possible to use || instead of an if-else statement by exploiting the property that the right-side operand of an || expression is evaluated only if the left-side operand evaluates to 0. Thus, the following two expressions are equivalent:

if (temperature > 50) ; else cout << "It is NOT too hot!" << endl; 
(temperature > 50) || cout << "It is NOT too hot!" << endl; 

Note, however, that many programmers object to the use of && and || operators to allow or block evaluation. They argue that, when an && or || operator is included in an expression, anyone who looks at the expression—other than the original programmer—naturally expects the value produced by the expression to be used. If the value is not used, the person who looks at the program might wonder whether the original programmer left out a portion of the program unintentionally.

Accordingly, some C++ compilers complain about using an && or || expression whenever the value of the expression is not actually put to use.