Home Segments Index Top Previous Next

289: Sidetrip

You can, if you wish, use conditional-operator expressions in place of if statements, as in the following example, in which one of the two output expressions is evaluated:

#include  
main ( ) { 
  int change; 
  cin >> change; 
  change == 1 ? cout << "The temperature has changed by " 
                     << change << " degree." << endl 
              : cout << "The temperature has changed by " 
                     << change << " degrees." << endl; 
} 
--- Data ---
1 
--- Result --- 
The temperature has changed by 1 degree. 

This program not only reintroduces needless duplication, but also introduces a conditional-operator expression that is not inside any other expression that can make use of the value produced. Instead, the conditional-operator expression forms a complete statement. Such use of the conditional operator is considered poor programming practice, and your C++ compiler should issue a warning.