herring
herring

Reputation: 21

the k&r c answer book exercise 1.13

I am studying this book but unfortunately get stucked in this question, I google others answer but I still have something that I don't understand

#include <stdio.h>
#define MAXHIST 15
#define MAXWORD 11
#define IN 1
#define OUT 0

main() {
  int c, i, nc, state;
  int len;
  int maxvalue;
  int ovflow;
  int wl[MAXWORD];

  state = OUT;
  nc = 0;
  ovflow = 0;

  for (i = 0; i < MAXWORD; ++i)
    wl[i] = 0;
  while ((c = getchar()) != EOF) {
    if (c == ' ' || c == '\n' || c == '\t') {
      state = OUT;
      if (nc > 0)
        if (nc < MAXWORD)
          ++wl[nc];
        else
          ++ovflow;
      nc = 0;
    } else if (state == OUT) {
      state = IN;
      nc = 1;
    } else
      ++nc;
  }
  maxvalue = 0;
  for (i = 1; i < MAXWORD; ++i)
    if (wl[i] > maxvalue)
      maxvalue = wl[i];

  for (i = 1; i < MAXWORD; ++i) {
    printf("%5d - %5d : ", i, wl[i]);
    if (wl[i] > 0) {
      if ((len = wl[i] * MAXHIST / maxvalue) <= 0)
        len = 1;
    } else
      len = 0;
    while (len > 0) {
      putchar('*');
      --len;
    }
    putchar('\n');
  }
  if (ovflow > 0)
    printf("There are %d words >= %d\n", ovflow, MAXWORD);

  getchar();
  return 0;
}

Here I can understand the most of code here, but what the meaning of less than 0?

  for (i = 1; i < MAXWORD; ++i) {
    printf("%5d - %5d : ", i, wl[i]);
    if (wl[i] > 0) {
      if ((len = wl[i] * MAXHIST / maxvalue) <= 0)
        len = 1;
    } else
      len = 0;
    while (len > 0) {
      putchar('*');
      --len;
    }
    putchar('\n');
  }

I know the author try to nomorize the "len",but why the len is less than 0? Why does it happed? I think it is postive value. In the condition of "if( )" ,the "wl[i]" is positive.

Upvotes: 0

Views: 267

Answers (1)

Paul Ogilvie
Paul Ogilvie

Reputation: 25286

You refer to if ((len = wl[i] * MAXHIST / maxvalue) <= 0).

Since any wl[i] will be >=0, and MAXHIST is >0 and maxvalue will be >=0, then indeed len will never be less than zero and a comparison of ==0 would suffice.

However, always testing for the largest valid range is considerd good programming and is called "defensive programming" as it guards the program against current and future errors.

Example: would MAXHIST be made very large in the future, and wl[i] could become very large in the future, then the multiplication could wrap, resulting in a negative value.

Upvotes: 3

Related Questions