Adding else to the if Statement

The simple form of an if statement gives you the choice of executing a statement (possibly compound) or skipping it. C also enables you to choose between two statements by using the if else form. Let's use the if else form to fix an awkward segment from Listing 7.1.

if (all_days != 0)
  printf("%d days total: %.1f%% were below freezing.\n",
         all_days, 100.0 * (float) cold_days / all_days);
if (all_days == 0)
  printf("No data entered!\n");

If the program finds that days is not equal to 0, it should know that days must be 0 without retesting, and it does. With if else, you can take advantage of that knowledge by rewriting the fragment this way:

 if (all_days!= 0) printf("%d days total: %.1f%% were below freezing.\n", ...

Get C Primer Plus, Fourth Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.