xiaozaiz
xiaozaiz

Reputation: 69

Enums in declaring functions

I'm having some trouble understanding the code below. I have no clue as to how to declare a function using enums (or maybe i'm understanding my assignment wrongly?) Think

int words_starting_with() 

vs

enum Status words_starting_with()

Would appreciate if someone could give a quick explanation or direct me to more information.

(im not looking for written codes, just an explanation to help me complete my assignment would do)

enter image description here

Upvotes: 0

Views: 108

Answers (1)

David Ranieri
David Ranieri

Reputation: 41045

Here you are asked to fill a passed variable num_word and return the state of the function, is a common way to check errors:

enum Status {STATUS_OK, FILE_ERR_OPEN, NOT_FOUND};

enum Status words_starting_with(char const *dict, char letter, int *num_word)
{
    FILE *f = fopen(dict, "r");

    if (f == NULL)
    {
        return FILE_ERR_OPEN;
    }

    char str[100];

    while (fgets(str, sizeof str, f))
    {
        if (*str == letter)
        {
            *num_word++;
        }
    }
    return *num_word == 0 ? NOT_FOUND : STATUS_OK;
}

As you can see, the enum is self-documenting the result of the function, now compare:

int num_word = 0;

switch (word_starting_with("dict.txt", 'a', &num_word))
{
    case FILE_ERR_OPEN:
        perror("fopen");
        exit(EXIT_FAILURE);
    case NOT_FOUND:
        puts("dict doesn't contain words starting with 'a'");
        break;
    case STATUS_OK:
        printf("%d words starting with 'a'\n", *num_word);
        break;
}

with

int num_word = 0;

switch (word_starting_with("dict.txt", 'a', &num_word))
{
    case 1:
        perror("fopen");
        exit(EXIT_FAILURE);
    case 2:
        puts("dict doesn't contain words starting with 'a'");
        break;
    case 0:
        printf("%d words starting with 'a'\n", *num_word);
        break;
}

The first version is more clear and less prone to errors because you can even change the order of the constants in the enum and the result is still valid, also, as pointed out by @KeevinBoone in comments, the compiler can perform some additional checks:

switch (word_starting_with("dict.txt", 'a', &num_word))
{
    case FILE_ERR_OPEN:
        perror("fopen");
        exit(EXIT_FAILURE);
    case STATUS_OK:
        printf("%d words starting with 'a'\n", *num_word);
        break;
}

raises

warning: enumeration value ‘NOT_FOUND’ not handled in switch

Upvotes: 1

Related Questions