What is the point of allowing an identifier for enum?

Viewed 1607

Why doesn't the compiler complain when I try to assign incorrect values to variable a of type enum answer?

#include <stdio.h>

int main()
{
    enum answer {NO, YES};
    enum gender {MALE, FEMALE};

    enum answer a = 5; /* Assign an invalid value. */
    printf("answer: %d\n", a);

    a = MALE; /* Assign a value of wrong type */
    printf("answer: %d\n", a);

    return 0;
}

Here is the output:

$ gcc -std=c99 -pedantic -Wall -Wextra enum.c 
$ ./a.out
answer: 5
answer: 0

If enum doesn't lead to type-checking, then what is the point of having the syntax as:

enum [identifier] {enumerator-list}

I used answer and gender as the identifier for my enum. What is the point of allowing this syntax?

I mean this code could be very well written as

enum {NO, YES};
enum {MALE, FEMALE};

What is the point of allowing this syntax?

enum answer {NO, YES};
enum gender {MALE, FEMALE};
3 Answers
Related