Home Segments Index Top Previous Next

168: Mainline

So far, you have learned how to use if-else statements to execute one of two embedded computation-performing statements. You should also know about C's conditional operator, which enables you to compute a value from one of two embedded, value-producing expressions.

The conditional operator sees frequent service in display statements, where it helps you to produce the proper singular–plural distinctions. Consider, for example, the following program, which displays a price change:

#include  
main ( ) { 
  int change; 
  scanf ("%i", &change); 
  if (change == 1)  
     printf ("The price has changed by %i point.\n", change); 
  else 
     printf ("The price has changed by %i points.\n", change); 
} 
--- Data ---
1 
--- Result --- 
The price has changed by 1 point. 

The program works, but most C programmers would be unhappy, because there are two separate output statements that are almost identical. Such duplication makes programs longer, and the longer a program is, the greater the chance that a bug will creep in.

Accordingly, it would be safer to move the variation—the part that produces either the word point or the word points—into a value-producing expression inside a single display statement.