Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why enumeration objects can have values other than their enumerators in C? [duplicate]

Tags:

c

Here is my code:

#include <stdio.h>
int main()
{   
    enum C {green = 5, red};
    enum CC {blue, yellow} cc = green;
    printf("%i\n", cc);
    return 0;
}

It does compile, and produce console output 5.

cppreference.com says that "An enumerated type is a distinct type whose value is restricted to one of several explicitly named constants (enumeration constants)". I am really confused.

By the way, the compiler I'm using is gcc version 4.8.1.

like image 815
Carousel Avatar asked Dec 24 '22 09:12

Carousel


1 Answers

You're reading C++ documentation to learn about C? C and C++ are not the same language.

In C, an enum is effectively an integer type and you're allowed to handle it as such. This means that you can assign an integer to it which may not be one of the prescribed values.

However it's considered bad practice to do so and some compilers or static code checkers have options to warn about such practices.

In C++ on the other hand, enums are distinct types in their own right and you are not allowed to do this in C++, at least not implicitly. Compiling this as C++ results in a compilation error.

like image 193
skyking Avatar answered May 19 '23 13:05

skyking