Enum in C does not cause an error when typing incorrectly

I am using gcc and I compiled this code and it should have caused an error, but it worked successfully.

enum DIRECTION {EAST,WEST,NORTH,SOUTH};

int main(void) {
    enum DIRECTION currentDirection = 10;
    printf("%d\n",currentDirection);
    return 0;
}

EXIT: 10

+3
source share
3 answers

The type of transfers is defined in the draft draft of C99 Listing qualifiers 6.7.2.2as:

Each numbered type must be compatible with char, a signed integer type, or an unsigned integer type. The choice of type is determined by implementation, 110) [...]

where the note 110reads:

An implementation may delay the choice of an integer type until all enumeration constants are visible.

, , , Annex I , :

, , , , , (6.7.2.2).

gcc , clang -Wassign-enum -Weverything :

: "enum DIRECTION" [-Wassign-enum]

-Werror, .

:

  • -Werror clang , . C.
  • enum DIRECTION currentDirection = 128; , char.
+4

C enum int. .

+3

An enum () - , , . . - .

enum . , enum, .

, . , . - , , ( ).

It is also convenient to add a new symbolic name later and allow the values ​​to reorder themselves. However enum, the are Cnot strictly typified and compatible with whole characters. This way you can assign any value to a type variable enum.

// APPLE == 0, PEARS == 1, ...

enum fruits {APPLE, PEARS, BANANA};

// APPLE == 0, MANGO == 1, PEARS == 2, ...

enum fruits {APPLE, MANGO, PEARS, BANANA};
enum color {APPLE, PEACH};

enum color my_color = MANGO;  // not strongly typed
enum fruits my_fruit = 7; // int -> enum fruits conversion

However, it enumis C++strongly typed.

enum class Traffic_light {red, yellow, green};
enum class Warning {green, yellow, orange, red};

Warning w = 1; // error. no int -> Warning implicit conversion
Traffic_light t = Warning::red; // type error. Warning::red is a different type
0
source

All Articles