Question regarding Exercise 1-13, from K&R 2nd edition

69 Views Asked by At

In this exercise, you're writing a program to print a histogram of the lengths of words in its input.

The following code is from "The C Answer Book":

#include <stdio.h>

#define MAXHIST 15  //  max length of histogram
#define MAXWORD 11  //  max length of a word
#define IN      1   //  inside a word
#define OUT     0   //  outside a word

//  print horizontal histogram

int main(int argc, const char * argv[]) {

    int c, i, nc, state;
    int len;                //  length of each bar
    int maxvalue;           //  maximum value for wl[]
    int ovflow;             //  number of overflow words
    int wl[MAXWORD];        //  word length counters
    
    state = OUT;
    nc = 0;                 //  numbers of chars in a word
    ovflow = 0;             //  number of words >= MAXWORD
    
    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;     //  beginning of a new word
        } else
            ++nc;       //  inside a new word
    }
    
}

The problem I'm having is within the while statement.

Below the three if statements, there's an else.

Xcode gives me an error warning, which says, "Add explicit braces to avoid dangling else".

What does this mean?

The only solution I've come up with is to place curly braces around the ++ovflow;, but that hasn't made the error warning go away.

The line Xcode highlights isn't the last else

Any help is appreciated!

1

There are 1 best solutions below

1
On

The warning is telling you to write your if statement like this:

if (condition1) {
    statement1;
    statement2;
} else if (condition2) {
    statement1;
    statement2;
} else {
    statement1;
}

Rather than:

if (condition1) {
    statement1;
    statement2;
} else if (condition2) {
    statement1;
    statement2;
} else
    statement1;

This avoid mistakes if you start trying to add additional statements to the else clause without adding braces.