0

This post is not about some issue I have with my own code but rather to understand the logic of the course's code.

In this code, which is a segment of the file speller.c, I cannot understand why there is the increment of word before checking it.

  1. If we are at the end of a word, we add \0 to the word_n[index].
  2. Then we increment word so it will be: word_n+1[index].
  3. Then we check word_n[index]?

I would use this order : 1, 3 and then 2. Why am I thinking the wrong way ?

    // we must have found a whole word

    else if (index > 0)
    {
        // terminate current word
        word[index] = '\0';

        // update counter
        words++;

        // check word's spelling
        getrusage(RUSAGE_SELF, &before);
        bool misspelled = !check(word);
        getrusage(RUSAGE_SELF, &after);

        // update benchmark
        time_check += calculate(&before, &after);

        // print word if misspelled
        if (misspelled)
        {
            printf("%s\n", word);
            misspellings++;
        }

        // prepare for next word
        index = 0;
    }

Thank you !

0

You're not incrementing word. You're incrementing words, which is another variable used to count how many words were found.

Those two variables are declared separately (one is a char array, the other is an int) here:

// prepare to spell-check
int index = 0, misspellings = 0, words = 0;
char word[LENGTH+1];

You increment words before checking word because words counts all the words found, not the correct spelled words.

So you increment the counter to say a word was found (even if that word is misspelled), then you check word, then you increment misspellings if that word is misspelled.

1
  • Oh god, that is right. Thank you for this enlightenment! I did not see the s of word -_- Nov 12 '16 at 17:16

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .