O'Reilly logo

C Primer Plus, Fourth Edition by Stephen Prata

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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", ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required