Home Segments Index Top Previous Next

171: Mainline

Because a conditional-operator expression, unlike an if statement, produces a value, you can place it inside another expression. In particular, a conditional-operator expression can be an argument in a printf expression, because C allows you to insert a character string into the string displayed by printf. You simply place %s in printf's first argument at the place where you want the character string.

In the following, for example, a conditional-operator expression appears inside a printf expression, solving the duplication problem encountered in Segment 168:

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

If the change is one point, the value returned by the Boolean expression, and subsequently displayed, is "point"; otherwise, the value returned and subsequently displayed is "points".