Home Segments Index Top Previous Next

163: Mainline

Note the ambiguity in the following nested if statement:

if (ratio > 10) 
  if (ratio < 30) 
     printf ("It is in the normal range.\n"); 
    else printf ("It is ?.\n"); 

With what should you replace the question mark: expensive or cheap? As laid out on the page, it seems that expensive is the right answer. Laid out another way, however, you might have the impression that cheap is the right answer:

if (ratio > 10) 
   if (ratio < 30) 
     printf ("It is in the normal range.\n"); 
  else printf ("It is ?.\n"); 

Because C pays no attention to layout, you need to know that C assumes that each else belongs to the nearest if that is not already matched with an else. Thus, the question mark would be replaced by expensive.